I have created a notification service for my application as following :
export class NotificationService {
private subject = new Subject<Notification>();
constructor() {}
getNotification(): Observable<any>{
return this.subject.asObservable();
}
success(title: string, message: string){
this.notif(NotificationType.SUCCESS, title, message);
}
error(title: string, message: string){
this.notif(NotificationType.ERROR, title, message);
}
technicalError(title:string, message: string){
this.notif(NotificationType.TECHNICAL_ERROR, title, message);
}
info(title: string, message: string){
this.notif(NotificationType.INFO, title, message);
}
warning(title: string, message: string){
this.notif(NotificationType.WARNING, title, message);
}
notif(type: NotificationType, title: string, message: string){
this.subject.next(<Notification>{ type: type, title: title, message: message});
}
And this is an example on how I use this service:
this.notificationService.success("Suppression", "L'enregistrement a été supprimée !");
And since I have a component which is shared between all my components which is the header, I have a subscribe for the notification service subject in it's ngOnInit function:
this.notificationService.getNotification().subscribe((notification: Notification) => {
this.notification.create(NotificationType[notification.type], notification.title, notification.message);
});
For the first time I run the application the code inside subscribe function is executed once when I call some notificationService function, but after that the code inside the subscribe function executes multiple times.
How can I solve this ?
<app-header></app-header>so the header will always appear.