Angular 6 subscribe Event on constructor called multiple times

1.5k Views Asked by At

In my component on constructor (Child Component) I add simple event

This is my code:

   this._modalService.onHidden.subscribe(
      result => {
        console.log("_modalService.onHidden");
        if(this.shown){
          this.shown = false;
          this._router.navigate(['.'], { relativeTo: this._route.parent });
        }
      }, error => console.log(error));

While opening this page on the first time this event called just one but when enter to the page again this event called twice and when entering 3 times this event called 3 times etc.

[BTW this happening also if i move the code on the ngOnInit Event and this happening also to another event ngrx store pipe that the event called multiple times ]

This is my route (maybe it is the reason)

const routes: Routes = [
  {
    path:':id' ,component:EventComponent,
    children:[
      {
      path:'o/:file'
      ,component:EventDetailComponent
    }]
  },
  {
    path:':id/:sub' ,component:EventComponent,
    children:[{
      path:'o/:file'
      ,component:EventDetailComponent
    }]
  }
];

enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

you should unsubscribe in OnDestroy...

in constructor:

this.mySubscription = this._modalService.onHidden.subscribe(...);

in onDestroy:

this.mySubscription.unsubscribe();