Reputation: 391
I need to the use the HTTP library to check for the existence of a file on the server. It's pretty simple, all I am doing is calling the following code:
private serverHeadRequest(): Observable<any> {
return this.http.head("theFileName.xxx")
.map(this.isResponseOkCallBack)
.catch(this.handleError);
}
private isResponseOkCallBack(res: Response) {
switch (res.status) {
case 404:
return false;
case 200:
return true;
default:
return false;
}
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
If the response is a 200 then the code works well. However I would like to simply return false on any other sort of response code.
I tried this as an alternative error handler which I thought would simply return false if there was an error however this didn't work.
private handleError(error: any) {
return Observable.create()
.map({
return false;
});
}
How can I get this working? Is there a way to ignore certain status codes?
Upvotes: 4
Views: 4610
Reputation: 391
This is what I ended up doing:
serverHeadRequest(): Observable<any> {
return this.http.head('someFileName.xxx')
.map(this.isResponseOkCallBack)
.catch(this.handleHEADError);
}
private isResponseOkCallBack(res: Response) {
switch (res.status) {
case 404:
return false;
case 200:
return true;
default:
return false;
}
}
private handleHEADError(error: any) {
return Observable.of(this.isResponseOkCallBack);
}
Upvotes: 1
Reputation: 7060
When there was an error (which is thrown on most non-2xx responses), isResponseOkCallBack
won't be called, because it jumps right into the .catch()
block.
Try mapping all successful requests to true and any errors to false.
this.http.head("theFileName.xxx")
.map(() => true) // or .map(res => (res.status === 200))
.catch(() => Observable.of(false));
Upvotes: 2
Reputation: 193311
Try think you can handle error like this:
// import 'rxjs/add/observable/of'
handleError() {
return Observable.of(false);
}
Also, note that in case of error, browser will still print HEAD <url> 404 (Not Found)
in console. You should not worry about this, most importantly that you handle it properly (but returning false
).
Upvotes: 5