我有一个很大的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)
}
...
}
答案 0 :(得分:2)
如果您以仅更改路由器参数值的方式导航,但是否则使用相同的路径,则组件不会被销毁,而是可以重复使用。
在2.3中,添加了对自定义重用策略的支持以覆盖此行为。
另见:
https://github.com/angular/angular/pull/13124允许提供自定义重用策略。
或者,您可以只订阅参数更改并在回调中进行初始化:
constructor(private rewardsDetailService: RewardDetailService, private activatedRoute: ActivatedRoute, private authService: AuthService, private router: Router) {
router.params.forEach(param => this.myInit(param['rewardName']);
}
答案 1 :(得分:2)
那么,你还有什么期望:)?如果你没有指定它,角度如何神秘地阻止你setInterval
。 eventListeners
和subscriptions
也是如此。你应该在ngOnDestroy
停止这些。
private _interval: number;
ngOnInit() {
this._interval = setInterval(() => {
console.log('QUANTITY: ', this.quantity);
}, 1000)
}
ngOnDestroy() {
clearInterval(this._interval);
}