i try to make an http.get
-Request with angluar/http
in Ionic 3. The request is correct, but I'm not able to catch the error.
My methods look like this:
finalize() { this.saveConfig().then(() => { loader.dismiss(); loader2.present(); this.checkApiServer().then((data) => { console.log(data); loader2.dismiss(); }).catch(err => { console.log('error', err); loader2.dismiss(); }); }); } checkApiServer() { this.http.get(this.configuration.server + 'ping').subscribe(data => { if (data.status == 200) { resolve('server available'); } else { reject(Error('server unan')); } }); }
If I'm hitting a correct endpoint everthing works, but if the server is not available, i can not catch the error.
Thank you so much for your help
Greeetings
EDIT:
this is the completed method now:
finalize() { this.saveConfig().then(() => { loader.dismiss(); loader2.present(); this.checkApiServer().then((data) => { console.log(data); loader2.dismiss(); }).catch(err => { console.log('error', err); loader2.dismiss(); this.slides.lockSwipes(false); this.slides.slideTo(1); this.slides.lockSwipes(true); this.error = true; this.errorMessage = 'Der Api-Server konnte nicht erreicht werden. Stellen Sie sicher, dass Sie mit einem WLAN verbunden sind und er korrekte API-Server eingestellt ist.' }); }); } } checkApiServer() { return new Promise((resolve, reject) => { this.http.get(this.configuration.server + 'ping', { timeout: 3000 }).subscribe( (data) => { if (data.status == 200) { resolve('server available'); } else { reject(Error('server error')) } }, (err) => { reject(Error('server unreachable')); } ) }) }
THANKS!
i'm assuming you're hitting a timeout. you can pass an error handler along with the subscribe
as an arrow function like this :
//timeout is an optional setting optional here
this.http.get(this.configuration.server + 'ping', {headers: headers, timeout: 1000}).subscribe(
//we only hit this function when the subscribable returns an actual result (in this case, when the server answers)
(data) => {
if (data.status == 200) {
resolve('server available');
} else {
reject(Error('server error'));
}
},
//this is the default angular way of handling errors when using a subscribable
//so it should work for Ionic as well.
//we will only hit it if something goes wrong while waiting for our subscribable to finish
(err) => {
reject(Error('server unreachable?'));
}
});
He, you can use to the new HttpClient module of Angular 4.3, is too easy manage HTTP request.
this.http.get(this.configuration.server, {headers: headers}).subscribe(
(data) => {
// Here the code to execute when status code is 200
},
(err) => {
// Here when error
},
() => {
// and here the code to execute finally, (when http request finish)
}
});
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.