Access function of another Component (Angular5)

0

Suppose in my componentA I have a list of products. In my componentB I have a modal that registers my products. When registering a product, I want componentB to call a componentA function to update the product list .. How can I do this?

I've tried this and it does not work: link

att

    
asked by anonymous 26.02.2018 / 17:34

1 answer

1

Probably the modal is injected dynamically and is not always there to handle parent-child events.

For your problem, I suggest working with Global Events, this type of event, known as broadcast, can be heard from any application location, not just between direct descendants.

In this way, you would subscribe to this global event (which I call here 'refreshProducts') in your componentA:

refreshEvento: any = null;

ngOnInit() {
    this.refreshEvento = EventEmitterService.get('refreshProdutos').subscribe(e => this.carregaProdutos());
}

ngOnDestroy() {
    if (this.refreshEvento !== null) this.refreshEvento.unsubscribe();
}

And in your componentB, when updating or registering a new item, you would trigger this event:

salvarProduto() {
    // envia os dados para o servidor e no retorno dispara o evento global:
    EventEmitterService.get('refreshProdutos').emit(true);
}

So, everyone in any part of the application, who signed up for this event, will receive the signage and each one takes its action, in case, update the list.

There is an article that teaches you how to create these global events in Angular to be used as in the examples above: link

    
01.11.2018 / 15:01