Angular组件之间通信

痞子三分冷 提交于 2020-02-27 04:12:42

组合通信分为很多种;

  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://gitee.com/Z_xw/note/tree/master/angular/angular-demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!