我想在ionic2 app中检测慢速互联网并处理它。
我已经完成谷歌和方法使用settimeout是被允许但我怎么能在调用api时使用它?
我将api称为:
AppSettings.API_ENDPOINT = is a constant having api url.
this.returned = this.http.post(`${AppSettings.API_ENDPOINT}login`, "email=" + email + "&password=" + password, { headers: headers }).timeout(100).map(res => res.json()).subscribe(data => {
this.conn_error_msg = '';
if (data.status == 200) {
}
else {
}
},
error => {
this.isDisabled = 0;
this.conn_error_msg = 'Internet connection error. Please try again.';
console.log(JSON.stringify(error.json()));
loader.dismiss();
}
);
我的超时工作正常,但我需要显示警告..
如果超时,我希望在此处显示警告
解决:
this.http.get(url)
.timeout(1000) 。地图(...) .subcribe((success)=> {...},(错误)=> {//处理超时错误。});
希望它有所帮助。
快乐的编码。
答案 0 :(得分:2)
您可以在调用api时设置超时,如下所示:
import 'rxjs/add/operator/timeout';
return this.http.get(yourUrl).timeout(50000, new Error('Timeout!'));
当然,使用post / put ...方法时也可以这样做。
答案 1 :(得分:0)
您可以执行以下操作:
let returned = false;
startCallTime(slowConnectionLimit){
setTimeout(() => {
if(returned){
// IS NOT SLOW
} else {
// IS SLOW. SHOW YOUR MESSAGE
}
}, slowConnectionLimit)
}
callApi = () => {
startCallTime(30000); // WILL DETECT SLOW CONNECTION AFTER 30 SECONDS
this.http.get().then((res) => {
returned = true; // HERE YOU KNOW IF THE CALL HAS ENDED
});
}
我认为@sebaferreras的回答更干净,但只对rxjs有用...