Reputation: 3854
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
Upvotes: 0
Views: 365
Reputation: 647
Don't use any type. Use camelCase convention of variable names. In your service:
interface IData {
userId: number;
nav: string;
}
class ListService {
private list$ = new BehaviorSubject<IData>(null);
getList(): Observable<IData> {
return this.list$.asObservable().pipe(sharedReplay(1));
}
setList(data: IData): void {
this.list$.next(data);
}
}
In .ts file:
routing(nav: string): void {
const jsons = {
userId: this.UserId,
nav,
};
this.service.setList(jsons);
}
In component class:
ngOnInit(): void {
this.service.getList
.subscribe(console.log); // your data
}
I guess it will help.
Upvotes: 0
Reputation: 290
I think in that case you can use RxJs take operator.
this.Service.List.pipe(take(1)).subscribe(response => {
console.log(response);
});
Upvotes: 1
Reputation: 52847
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.
Upvotes: 2