Angular組件之間通訊

組合通訊分爲不少種;git

  1. 父向子(數據綁定)(@Input())
  2. 子向父(事件監聽)(EventEmitter)
  3. 經過公共服務(使用 rxjs)

特別須要注意: 這個公共服務須要在同一個註冊器下,好比在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

相關文章
相關標籤/搜索