Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2, can Http.get ignore 404

Tags:

angular

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?

like image 304
JT-Helsinki Avatar asked Mar 11 '23 09:03

JT-Helsinki


2 Answers

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).

like image 183
dfsq Avatar answered Mar 15 '23 08:03

dfsq


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));
like image 44
j2L4e Avatar answered Mar 15 '23 09:03

j2L4e