Angular 2 component to component communication

2019-09-09 01:28发布

问题:

I have a top menu (Component) that displays a list of models, and a side menu (Component) that displays a list of colors. In the center of my page I have a table (Component) that displays a list of things based on the user selections of color and model controls. None of the controls is a child of any other. The table component is rendered in a router-outlet container.

How can I make the table component listen for property changes in the two menu components?

I have already tried a session service as described here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-servicehttps://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

It does not work because the table component is not a child of the menu components.

回答1:

I would make simple service for it:

@Injectable()
export class FilterService {
    public modelChange$:EventEmitter;
    public colorChange$:EventEmitter;

    constructor(){
        this.modelChange$ = new EventEmitter();
        this.colorChange$ = new EventEmitter();
    }

    public setModel(model):void{
        this.modelChange$.emit(model);
    }

    public setColor(color):void{
        this.colorChange$.emit(color);
    }
}

Then TopMenuComponent and SideMenuComponent will invoke the service's setters:

constructor(private _filterService:FilterService){}
// method invoked by user's action
onSelect(value) {
    this._filterService.setModel(value); // or setColor()
}

and TableComponent will subscribe for the events:

constructor(private _filterService:FilterService){
    this._filterService.modelChange$.subscribe(model => console.log("new model: " + model));
    this._filterService.colorChange$.subscribe(color => console.log("new color: " + color));
}

I used my interior artist to show how it would work:

Hope it helped.



标签: angular