组合通讯分为不少种;git
特别须要注意: 这个公共服务须要在同一个注册器下,好比在root注册器下,若是不在可能会出现订阅不到的问题typescript
// 服务 @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-demoide