我正在使用getData函数向rest API发出请求(请参阅代码)。如果由于某种原因请求失败,我会再次调用getData函数,直到成功为止。
问题是:如果我弹出页面,请求仍然会被发送(循环仍然会运行)。
如何关闭页面以便代码执行停止?现在我用pop来关闭页面。
// Imports ...
export class RecipePage {
constructor(public navCtrl: NavController, public navParams: NavParams, private http: HttpClient)
{
this.getData();
}
getData() {
this.http.get('http://localhost:8000/get/recipes')
.subscribe(
data => {
console.log(data);
},
error => {
console.log('retrying ...');
// !! This loop continues after the page is popped !!
setTimeout( () => {
this.getData();
}, 2000);
},
);
}
}
答案 0 :(得分:0)
离开该页面后,您可以clearTimeout
清除 setTimeout
:
// Imports ...
export class RecipePage {
private timeout: any;
constructor(...) {}
ionViewWillEnter() {
// Try to get the data when entering to the page
this.getData();
}
ionViewWillLeave() {
// Clear the timeout to prevent making request after leaving the page
if(this.timeout) {
clearTimeout(this.timeout);
}
}
getData() {
this.http.get('http://localhost:8000/get/recipes')
.subscribe(
data => {
console.log(data);
},
error => {
console.log('retrying ...');
if(this.timeout) {
// Prevent multiple setTimeouts at the same time
clearTimeout(this.timeout);
}
// Store a reference in the timeout property
this.timeout = setTimeout(() => { this.getData(); }, 2000);
},
);
}
}
请注意以下几点:
constructor
中发出http请求。请使用IonViewWillLoad
/ IonicViewWillEnter
/ ...或任何其他生命周期挂钩setTimeout
不是重试http请求的最佳方法。请查看 this blog post ,了解如何使用RxJ重试Http请求