简体   繁体   中英

Service subscription initiate multiple time inside ngOnInit [Angular 2]

I have problem that when i go to diffent pages and return bank to first page where is this component:

ngOnInit() {
  this.getModal();
}

getModal() {

this.subscription = this.sharedService.itemEdit$.subscribe((bank: any) => {
            console.log("TEST")
            this.subscription.unsubscribe();
        });
}

I get multiple subsciption even I call emit service just one time.

Anyone know what can be a problem?

You need to unsubscribe inside ngOnDestroy just before Angular destroys the directive/component.Check Angular Lifecycle hook

ngOnDestroy() {
  if(this.subscription) {
    this.subscription.unsubscribe();
  }
}

An alternative to ranakrunal9's answer , that might be helpful if you have multiple subscriptions, is to setup a destroyed$-trigger and use .takeUntil(this.destroyed$) :

class SomeComponent {
    destroyed$ = new Subject();

    ngOnInit() {
        this.sharedService.itemEdit$
            .takeUntil(this.destroyed$) // this will automatically complete the stream when destroyed and therefor close the subscription
            .subscribe(...);

        this.sharedService.otherStream$
            .takeUntil(this.destroyed$)
            .subscribe(...);

        this.sharedService.streamThree$
            .takeUntil(this.destroyed$)
            .subscribe(...);
    }

    ngOnDestroy() {
        this.destroyed$.next();
    }
}

As an additional side-note: Try to avoid manual subscriptions in components, a component is usually there to display data, for which the async -pipe can be used, which will handle subscribe and unsubscribe automatically so you don't have to worry about all that.

If something perpetual(like a background-task) is going on, use a service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM