Angular 8 中条件变为真时,如何设置间隔停止的条件?
How to set a condition for interval to stop when condition become true in 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
设置为未定义。当我在 ngOnDestroy
中 console.log(this.groupId)
它打印 undefined
但间隔继续拨打电话。
服务文件:
getGaugeData(groupId:any){
return this.http.get(this.path, {headers: {'tokenid': this.tokenId},params: {groupId: '3133'})
.toPromise().then(res => {
return res;
});
}
我没看错,你需要取消订阅Observable,那么,只需要调用这个function.You就可以使用doCheck,在groupId变为undefined之前调用ensure,取消订阅。
doCheck() {
if(!this.groupId) {
unsuscribe().
}
}
我想在变量未定义时停止进行 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
设置为未定义。当我在 ngOnDestroy
中 console.log(this.groupId)
它打印 undefined
但间隔继续拨打电话。
服务文件:
getGaugeData(groupId:any){
return this.http.get(this.path, {headers: {'tokenid': this.tokenId},params: {groupId: '3133'})
.toPromise().then(res => {
return res;
});
}
我没看错,你需要取消订阅Observable,那么,只需要调用这个function.You就可以使用doCheck,在groupId变为undefined之前调用ensure,取消订阅。
doCheck() {
if(!this.groupId) {
unsuscribe().
}
}