Angular组件之间通信

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

组合通信分为很多种;

  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;
  });
}


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_7294