Angular2-更改页面时组件保持运行 [英] Angular2 - Component keeps running when change page
问题描述
我有一个大型Angular2应用.我拥有的一条路线是/rewards
,这是我们提供的所有奖励的列表.我的另一条路线是/reward/{rewardName}
,它是单个奖励详细信息页面.我遇到的问题是,当我在/reward
路由和不同的/reward/{rewardName}
路由之间来回切换时,所有/reward我点击的/{rewardName}
页面继续运行.我知道这是因为我的/reward/{rewardName}
组件的 ngOnInit
中有一个 setInterval
.因此,如果我点击/reward/{rewardName}
路由5次,它将注销5个 quantity
实例,如下面的代码所示.为什么此组件永远不会停止运行?(无论我在网站的其余部分进入哪个页面,都可以继续运行)
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)
代码:
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)
}
...
}
推荐答案
那么,您还期望什么:)?如果您不指定角度,角度如何神秘地阻止您的 setInterval
. eventListeners
和 subscriptions
也是如此.您应该在 ngOnDestroy
上停止这些操作.
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);
}
这篇关于Angular2-更改页面时组件保持运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!