Angular组件之间通信基础入门_通信新手入门

组合通信分为很多种;父向子(数据绑定)(@Input())子向父(事件监听)(EventEmitter)通过公共服务(使用 rxjs)特别需要注意: 这个公共服务需要在同一个注册器下,比如在root注册器下,如果不在可能会出现订阅不到的问题 // 服务@Injectable({providedIn: ‘root’})export class Ind

Angular组件之间通信基础入门

组合通信分为很多种;

Angular组件之间通信基础入门_通信新手入门

  1. 父向子(数据绑定)(@Input())
  2. 子向父(事件监听)(EventEmitter)
  3. 通过公共服务(使用 rxjs)

特别需要注意: 这个公共服务需要在同一个注册器下,比如在root注册器下,如果不在可能会出现订阅不到的问题  

    // 服务
    @Injectable({providedIn: 'root'})
    export class IndexTitleService {

     _title = new Subject<string>();
     _describe = new Subject<string>();

     titleSubscribe = this._title.asObservable();
      describeSubscribe = this._describe.asObservable();

    constructor() {

    }

    changeTitle(title: string) {
      this._title.next(title);
    }

    changeDescribe(des: string) {
      this._describe.next(des);
    }

    }
// A组件 产生变化 
constructor(private titleService: IndexTitleService) {
    titleService.changeTitle('欢迎');
}
  // B组件 接收变化
constructor(private location: Location, private titleService: IndexTitleService) {
  this.titleSub = titleService.titleSubscribe.subscribe(value => {
    this.title = value;
  });
  this.desSub = titleService.describeSubscribe.subscribe(value => {
    this.describe = value;
  });
}
海计划公众号
(0)
上一篇 2020/03/23 08:59
下一篇 2020/03/23 08:59

您可能感兴趣的内容