I have a MessagesService, where i can sendMessage and getMessage:
export class MessagesService {
constructor() { }
private subject = new Subject<any>();
sendMessage(message: string): void {
this.subject.next({ text: message });
}
clearMessages(): void {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
In the MessagesComponent i call the getMessage method:
export class MessagesComponent implements OnInit {
message: any = {};
subscription: Subscription;
constructor(public messagesService: MessagesService) {
this.subscription = this.messagesService.getMessage().subscribe(message => { this.message = message; });
}
And also in its template:
{{message?.text}}
Now in another component, where I use sendMessage (in the .ts file) and put a string in it, I call in its template
Now my question: is it correct to put this into the brackets of the constructer of this file:
constructor(private heroService: HeroService, private route: ActivatedRoute, private enemyService: EnemyService,
public messagesService: MessagesService) {
this.subscription = this.messagesService.getMessage().subscribe(message => {
if (message) {
this.messages.push(message);
} else {
// clear messages when empty message received
this.messages = [];
}
});
}
There is what we call life cycle hooks in Angular. It's ok to add your subscription in your constructor or in 'ngOnInit' to ensure that the component is already initialized.