如何解决当Angular 8中的条件变为真时,如何设置间隔停止的条件?
当变量未定义时,我想停止进行API调用。
ngOnInit() {
// Set time interval to update data again and again
const source = interval(3000);
if(this.groupId){
this.subscription = source.subscribe(
val => this.mrDataService.getGaugeData(this.groupId).then(
data => {
if(this.groupId){
console.log(data)
}
},error => {
console.log('Something Went Wrong')
}
)
);
}
}
ngOnDestroy(){
this.groupId=undefined;
}
销毁组件时,我需要将this.groupId
设置为undefined。当我在console.log(this.groupId)
中ngOnDestroy
时,它会打印undefined
,但间隔会继续打电话。
服务文件:
getGaugeData(groupId:any){
return this.http.get(this.path,{headers: {'tokenid': this.tokenId},params: {groupId: '3133'})
.toPromise().then(res => {
return res;
});
}
解决方法
我不会误会,您需要取消对Observable的订阅,然后只需要调用此函数即可。您可以使用doCheck(取消确认groupId之前取消调用)并取消订阅该怀疑。
doCheck() {
if(!this.groupId) {
unsuscribe().
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。