I have this navigation bar
<span (click)="routing('settings')">
Settings
</span>
in ts file
routing(data) {
let jsons = {
UserId: this.UserId,
Nav: data,
};
this.Service.List.next(jsons);
}
in service file
List= new BehaviorSubject<any>('');
when i click on settings menu subscribe it in next component oninit method
ngOnInit(): void {
this.Service.List.subscribe(response => {
console.log('function called ');
}
}
Issue is sometime ngOnInit is not called still subscribe method is called multiple times upto 10-15 times, i want to resolve this issue if i click on navigation bar link it should subscribe only once, this happend only when subscribe gets called before ngOninit.
Any solution Thanks
CodePudding user response:
Since your service has a longer lifetime than your component, you have to cleanup your subscriptions every time your component gets destroyed:
destroy$ = new Subject<void>()
ngOnInit(): void {
this.Service.List.pipe(takeUntil(this.destroy$)).subscribe(response => {
console.log('function called ');
}
}
ngOnDestroy(): void {
this.destroy$.next()
}
ngOnInit
and ngOnDestroy
are guaranteed to be called exactly once per component lifetime.
CodePudding user response:
I think in that case you can use RxJs take operator.
this.Service.List.pipe(take(1)).subscribe(response => {
console.log(response);
});