Angular2 - 组件在更改页面时保持运行

时间:2017-02-22 15:27:25

标签: angular

我有一个很大的Angular2应用程序。我有一条路线是/rewards,这是我们提供的所有奖励的清单。我的另一条路线是/reward/{rewardName},这是一个单一的奖励详情页面。我遇到的问题是,当我在/rewards路由和不同/reward/{rewardName}路由之间切换回第四个时,我所点击的所有/reward/{rewardName}页面都会继续运行。我知道这一点,因为我的setInterval组件ngOnInit中有一个/reward/{rewardName}。因此,如果我点击/reward/{rewardName}路由5次,它将注销5个quantity个实例,如下面的代码所示。为什么这个组件永远不会停止运行? (无论我在网站的其他部分访问哪个页面,都继续运行)

代码:

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) 
      }

    ...
}

2 个答案:

答案 0 :(得分:2)

如果您以仅更改路由器参数值的方式导航,但是否则使用相同的路径,则组件不会被销毁,而是可以重复使用。

在2.3中,添加了对自定义重用策略的支持以覆盖此行为。

另见:

或者,您可以只订阅参数更改并在回调中进行初始化:

constructor(private rewardsDetailService: RewardDetailService, private activatedRoute: ActivatedRoute, private authService: AuthService, private router: Router) { 
  router.params.forEach(param => this.myInit(param['rewardName']);
}

答案 1 :(得分:2)

那么,你还有什么期望:)?如果你没有指定它,角度如何神秘地阻止你setIntervaleventListenerssubscriptions也是如此。你应该在ngOnDestroy停止这些。

private _interval: number;

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


ngOnDestroy() {
    clearInterval(this._interval);
}