user12428054
user12428054

Reputation: 135

Inside ngOnint() service method called more than once

  ngOnInit() {
    this.store.pipe(select(empReducer.getErrorStatus)).subscribe(err => this.Error = err);
    this.store.pipe(select(empReducer.getEmpInfo)).subscribe(res=> console.log('test'));
}

Console called more than one time why?

Upvotes: 1

Views: 161

Answers (2)

Chogainz
Chogainz

Reputation: 37

As previously advised check the response to see what you are subscribing to. Regarding the subscriptions, you could use this pattern to ensure that all subscriptions get unsubscribed when the component is destroyed. Hope this helps.

private _subscriptions: Subscription = new Subscription();

public ngOnInit():void {

  this._subscriptions.add(
    this.store.pipe(select(empReducer.getErrorStatus)).subscribe(err => this.Error = err)
    )
  );

  this._subscriptions.add(
    this.store.pipe(select(empReducer.getEmpInfo)).subscribe(res => console.log('test')
    )
  );
}

public ngOnDestroy(): void {
    this._subscriptions.unsubscribe();
}

Upvotes: 1

mbojko
mbojko

Reputation: 14679

I see only two possibilities:

  1. empReducer.getEmpInfo emits more than once.

  2. As in the code you provided, there's a subscription, but there's no unsubscription (either with unsubscribe(), or with the takeUntil pattern) on destroy. If the component is created, destroyed, created again (say, the user goes to another view and back again), you'll have two or more active subscriptions.

Upvotes: 3

Related Questions