Issue
Hi I have following problem in my Angular 2 app.
I have BroadcastService:
@Injectable()
export class BroadcastService {
private broadcastSubject: BehaviorSubject<Event> = new BehaviorSubject<Event>(0);
public next(event: Event): void {
return this.broadcastSubject.next(event);
}
public subject(event: Event): Observable<Event> {
return this.broadcastSubject.asObservable().filter(e => e === event);
}
}
Which I use in components like this:
export class MyComponent implements OnInit {
constructor(public broadcastService: BroadcastService) {
this.broadcastService.subject(Event.BLA_EVENT).subscribe(() => this.bla());
}
...
Whenever I route to '/mycomponent' the MyComponent.constructor is called, so the Event.BLA_EVENT is subscriped multiple times.
Any advice how to prevent multiple time subscription?
Solution
Manual subscriptions inside components should always be unsubscribed in the ngOnDestroy
hook. This is to prevent memory leaks, unwanted double subscriptions, and errors occuring if you change something inside the component after it has been destroyed:
export class MyComponent implements OnInit, OnDestroy {
private _broadSub;
constructor(public broadcastService: BroadcastService) {}
ngOnInit() {
this._broadSub = this.broadcastService.subject(Event.BLA_EVENT).subscribe(() => this.bla());
}
ngOnDestroy() {
this._broadSub.unsubscribe();
}
}
Answered By - Poul Kruijt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.