RXJS組件間超越父子關係的相互通訊

RXJS組件間超越父子關係的相互通訊

用到這個的需求是這樣的: 組件A有數據變化,將變化的數據流通知組件B接收這個數據流並作相應的變化this

實例化RXJS的subject對象

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
/**
 * 事件總線,組件之間能夠經過這個服務進行通信
 */
@Injectable()
export class EventBusService {
    public maintenance: Subject <any> = new Subject<any>();
    constructor() { }
}

這裏經過一個對象類,封裝了,能夠單獨寫code

在組件A中發送數據流

this.maintenanceService.getFlowChart(data.status).subscribe(res => {
   this.eventBusService.maintenance.next(res);
});

在組件B監聽數據流的變化,並接收數據流

this.eventBusService.maintenance.subscribe((data) => {
    if (data) {
        alert(data);
    }
 });
相關文章
相關標籤/搜索