Angular 2 => notify a route component of an event in the app component

强颜欢笑 提交于 2019-11-30 16:31:35

There's also the possibility of just using a shared service to communicate between different components, e.g. via a messenger service like this:

MessengerService

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class MessengerService {
    private messageSource: BehaviorSubject<boolean> = new BehaviorSubject(true); 
    public message = this.messageSource.asObservable();
    public buttonClicked(value: boolean) {
        this.messageSource.next(value);
    }
}

Parent Component

export class ParentComponent {
    constructor(private messengerService: MessengerService) { }
    addEntity() {
        this.messengerService.buttonClicked(true);
    }
}

Child Component

import { Subscription } from 'rxjs/Rx';
export class ChildComponent implements OnInit, OnDestroy {
    private messageSubscription: Subscription;
    constructor(private messengerService: MessengerService) { }
    ngOnInit() {
        this.messageSubscription = this.messengerService.message.subscribe(m => {
            // Act upon the click event
        });
    }
    ngOnDestroy() {
        this.messageSubscription.unsubscribe();
    }
}

This would be a clean way to decouple the components and rely on a messenger service (that you could subscribe to in multiple components, wherever it is required)

Well if I understand well your question try this: put a return value on the addEntity() method, can be an string, or something that you know the kind of thing that you are adding (heroes/contacts/pets). Then on the main template put a local variable that takes the return of the addEntity() method like this:

<button (click)='#type_added = addEntity()>Add</button>

then you can pass that "#type_added" local variable to the other component like this:

<router-outlet [added] = #type_added></router-outlet>

and you must declare in your router-outlet component (.ts) the variable "added" whidth the @Output.

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