Access another Component function (Angular5)

Asked

Viewed 2,710 times

0

  • 2

    I suggest that you start this list of products in a service by injecting the same into the components.

  • 1

    This also seems to me the best option though.. How will I keep this list in the service if it comes from an http request?

  • I managed to solve using the Eventemitter, I confess that I was not very satisfied.. In componentB, when entering a record I call the service that returns the products and update the list of the Place by passing the updated list via Eventemitter.. Finds this approach very bad?

  • 1

    why not create a Observable products? The service is the central guy who has the list of products. Who needs to reference the products gives a subscribe.

  • 1

    All right, this way is centralized the method that returns products.. It turns out that only using this concept does not solve my problem, because I am using this modal (https://ng-bootstrap.github.io/#/Components/modal/examples), ie the modal is a Component, which in practice is another scope.. After inserting a product into the modal, I need the parent list to be updated.. Only with observable cannot solve this problem.

  • Take a look at behavior Subject as in this example -> https://scotch.io/tutorials/3-ways-to-pass-async-datato-angular-2-child-components

Show 1 more comment

1 answer

3

Probably the modal is injected dynamically and is not always present to work with events between father and son.

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

That way, you would sign up for this global event (which I call here 'refreshProducts') in your website:

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 that event:

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

Thus, everyone, in any part of the application, who signed up for this event, will receive the signage and each takes his or her attitude, in case, update the list.

There is an article that teaches how to create these global events in Angular to be used as in the above examples: https://blog.wgbn.com.br/broadcast-de-eventos-no-angular-2-cb97a5ad6ff1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.