加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 如何使用共享服务将数据从一个组件发送到另一个组件

发布时间:2020-12-17 07:36:09 所属栏目:安全 来源:网络整理
导读:参见英文答案 How to share service between two modules – @NgModule in angular not between to components?5个 Angular – shared service between components doesn’t work2个 我想使用subject将数据发送到另一个组件(用于赚钱目的).我无法取回数据.这
参见英文答案 > How to share service between two modules – @NgModule in angular not between to components?5个
> Angular – shared service between components doesn’t work2个
我想使用subject将数据发送到另一个组件(用于赚钱目的).我无法取回数据.这是我的代码:

app.component.ts

import { Component } from '@angular/core';
import { shareService } from './share.service';

@Component({
 selector: 'my-app',template: `
  <hello></hello>
  <button (click)="passData()">
    Start
  </button>
  `,styleUrls: [ './app.component.css' ],providers:[shareService]
})
export class AppComponent  {
  constructor(private service : shareService){}

  passData(){
   this.service.send("hello");
}

}

hello.component.ts

import { Component,Input } from '@angular/core';
import { shareService } from './share.service';
import { Subscription }   from 'rxjs/Subscription';

@Component({
  selector: 'hello',template: `<h1>Hello!</h1>`,styles: [`h1 { font-family: Lato; }`],providers:[shareService]
})
export class HelloComponent  {
  subscription: Subscription;
    constructor(private share : shareService){
    this.subscription =  share.subj$.subscribe(val=>{
    console.log(val);
    })
  }
}

share.service.ts

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class shareService{

  private sub = new Subject();
  subj$= this.sub.asObservable();

    send(value: string) {
    this.sub.next(value);
  }

}

我没有在控制台中获得价值.

这是工作演示:DEMO

通过:
@Component({
  .....
  providers: [shareService]
})

在这两个组件中,您将创建共享servcie的两个不同实例.
每个实例都不“了解”每个组件的数据.
提供模块级别,它将工作.

@NgModule({
  ....
  providers: [shareService]
})

这样,您将服务作为单个实例注入到两个组件中,因此它们可以共享它,因为它们将共享数据.

demo

见also

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读