A. A.
A. A.

Reputation: 153

Subscribe method get call multiple times Angular 5

I have one method subscribed in ngOnInit of controller.ts. From the view, there is an option to select the different user from listing which redirects to the same page just ID from URL gets changed. Hence ngOnInit gets invoked multiple times. Hence method gets subscribed multiple times. A number of times we select different users method get invoked for each number of a member selected i.e. if we select 3 users one after another route gets changed 3 times hence method gets invoked 3 times when observable gets the result.But if we refresh the page everything works fine. but if I used unsubscribe in ngDestroy then it won't get subscribed again in ngOnInit. Is any solution for this.

 ngOnInit() { 
    this._myService.detailsReceived.subscribe((obj: details) => 
       {console.log(obj.text)}
    );
 }

the route change on same page is

this.route.navigate(['user-home', userid]);

I require this method to keep subscribed until user gets logout, hence canonot use subscribe.Take(1)

Upvotes: 1

Views: 10349

Answers (1)

Igor
Igor

Reputation: 62213

but if I used unsubscribe in ngDestroy then it won't get subscribed again in ngOnInit

From comments:

ngOnDestroy() { this._myService.detailsReceived.unsubscribe(); } I used this. Is it wrong way to unsubscribe?

You are not unsubscribing correctly. You have to unsubscribe from the Subscription, not the Observable. Unsubscribing to the observable causes exactly that behavior that you described.

// import 
import { Subscription } from 'rxjs';

///////

// In the component
detailRecivedSubscription: Subscription;
ngOnInit() { 
    this.detailRecivedSubscription = this._myService.detailsReceived.subscribe((obj: details) => 
       {console.log(obj.text)}
    );
}
ngOnDestroy() { 
    this.detailRecivedSubscription.unsubscribe();
}

Also in this scenario it might also make more sense to subscribe to this service in the/a root level component.

Upvotes: 11

Related Questions