I have the following method, using Ionic 2 with Angular 2:
private login(params: any, url: string){
var p = new Promise<JsonResult>((resolve, reject) => {
let body = JSON.stringify(params);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options)
.timeout(10000, new Error('Timeout exceeded during login'))
.subscribe((res) => {
let json = new JsonResult().deserialize(res.json());
resolve(json);
}, (err) => {
reject(err);
});
});
return p;
}
No matter what I do, the subscribe is not working as expected. The error handler never gets fired. Not even after the timeout has exceeded.
Is this a known problem, or is there something wrong with my syntax?
Any help would be appreciated.
If you want to return a Promise
I would do it this way:
private login(params: any, url: string){
let body = JSON.stringify(params);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body, options)
.timeout(10000, new Error('Timeout exceeded during login'))
.catch(err => {
console.log(err);
return Observable.of([]));
})
.map((res) => {
return new JsonResult().deserialize(res.json());
})
.toPromise();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.