How to execute a function on one component and affect another component - Angular 6

0

I would like to know how I can through a component affect another component in the angle 6. These components are not parent and child. They are different.

<app-navegacao></app-navegacao>
<router-outlet></router-outlet>

Where Open / Closed Quotes is my navigation bar: ""

And where is the table, my other component is part of a router-outlet:

I want to run the event associated with the green button and issue the values to my navigation bar

    
asked by anonymous 02.10.2018 / 20:02

2 answers

0

You can use an @Service with a BehaviorSubject. The BehaviorSubject contains the value that needs to be shared with other components, it at least time is Observer and Observable it can receive and issue the current values.

You will need a Service with an attribute of type BehaviorSubject, in my example I created the same with type number and a default value of 0, as below:

@Injectable()
export class QuoteService {
  public openQuotes = new BehaviorSubject<number>(0);

setOpenQuote(quotes : number){
   this.openQuotes.next(quotes);
}
}

In the Table component is where you will get the data, and send it to the BehaviorSubject, then you need to inject the Service into the Table component, and in the method called by the green button, you will send the data: / p>

construtor(
   quoteService : QuoteService 
){}

acaoBotaoVerde(){
   this.quoteService.setOpenQuote(quotesOpened);
}

And in the navigation component you will simply make a subscribe to be monitored if the information changes:

construtor(
   quoteService : QuoteService 
){}

this.quotesOpen = this.quoteService.openQuotes.subscribe(
   (quotes) => {
     return quotes;
   }
);

Of course, this code can be optimized, but it helps you get an idea of what to use.

    
02.10.2018 / 21:02
-1

Below is a simple example of how to trigger and listen to events from different contexts, what to do in each context will be described.

CONTEXT - Green button component service:

import { EventEmitter } from '@angular/core'; //import necessario

public eventoEmit = new EventEmitter<boolean>(); // seu emissor de evento

public Click_BotaoVerde()
{
    //demais ações 
    this.eventoEmit.emit(true); // emitindo o evento
}

CONTEXT - Component menu

constructor(private _btnVerdeService: BtnVerdeService){

  this._btnVerdeService.eventoEmit.subscribe(x => {
      // Aqui você já esta ouvindo os eventos do btn verde
    });
}
    
03.10.2018 / 19:18