1

I have a large Angular2 app. I one route I have is /rewards which is a list of all rewards we offer. Another route I have is /reward/{rewardName} which is a single reward detail page. The problem I am having is that when I switch back and fourth between the /rewards route and different /reward/{rewardName} routes, all of the /reward/{rewardName} pages that I have hit continue to run. i know this because I have a setInterval in the ngOnInit in my /reward/{rewardName} component. So if I hit the /reward/{rewardName} route 5 times, it will log out 5 instances of quantity, as shown in code below. Why does this component never stop running? (continues to run no matter what page I go to in rest of site)

Code:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RewardDetailService } from './reward-detail.service';
import { AuthService } from '../../auth/auth.service';

@Component({
  selector: 'reward-detail-component',
  styleUrls: [ './reward-detail.component.scss' ],
  templateUrl: './reward-detail.component.html'
})

export class RewardDetailComponent implements OnInit {
    ...
    quantity = 1;

    constructor(private rewardsDetailService: RewardDetailService, private activatedRoute: ActivatedRoute, private authService: AuthService, private router: Router) { ... }

     ngOnInit() {
        setInterval(() => {
          console.log('QUANTITY: ', this.quantity);
        }, 1000) 
      }

    ...
}
georgej
  • 3,041
  • 6
  • 24
  • 46

2 Answers2

2

If you navigate in a way that only a router parameter value is changed, but otherwise the same route is used, the component is not destroyed, but reused.

In 2.3 support for a custom reuse strategy was added to override this behavior.

See also:

Alternatively you can just subscribe to param changes and do your initialization in the callback:

constructor(private rewardsDetailService: RewardDetailService, private activatedRoute: ActivatedRoute, private authService: AuthService, private router: Router) { 
  router.params.forEach(param => this.myInit(param['rewardName']);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2

Well, what else would you expect :)? How can angular mysteriously stop your setInterval if you do not specify this. Same goes for eventListeners and subscriptions. You should stop these at ngOnDestroy.

private _interval: number;

ngOnInit() {
    this._interval = setInterval(() => {
      console.log('QUANTITY: ', this.quantity);
    }, 1000) 
}


ngOnDestroy() {
    clearInterval(this._interval);
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149