0

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

1
  • Unclear question, I guess you just need to unsubscribe in ngOnDestroy. Commented Jan 2, 2023 at 16:46

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

I think in that case you can use RxJs take operator.

this.Service.List.pipe(take(1)).subscribe(response => {
  console.log(response);
});

1 Comment

Thanks i tried it with take('1') then subscribe was not working then changed value to take(5) then it is working, what changes i have to make in my code
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.