How do I, while in service, call a function from the component that instantiated this service?
How do I, while in service, call a function from the component that instantiated this service?
In Angular2, the components should not be with business logic, these should be in Services, in the components should only be things related to the application template, things related to data manipulation must be in the Service.
You can communicate via Subject
, in the concept of sending and receiving messages.
For example, your service will have two functions, one that receives and one that sends.
@Injectable()
export class AlgumService{
private subject = new Subject<string>();
enviaMensagem(texto: string) {
this.subject.next(texto);
}
recebeMensagem(): Observable<string> {
return this.subject.asObservable();
}
}
At your other service, you call AlgumService
:
nomeMetodo() {
// envia mensagem
this.algumService.enviaMensagem('Seja bem vindo'):
}
and its Component
in OnInit()
, you get it:
this.algumService.recebeMensagem().subscribe(mensagem => {
console.log(mensagem); // Seja bem vindo
// chame sua funcao qualquer no componente
}, (error) => {
console.log(error);
})