0

I have question on HttpClient. I have GET method which it returns response 404 Not found with message. But my code dont gains response, but only string "Not found". How to change my code that it have http response with all attributes(status, message, body...)? Thanks

try {
        let response = await this.httpClient
           .get(environment.serverUrl + 'api/user/1',  { observe: 'response' })
           .toPromise();
        console.log(response); //object with status, message...
     catch (error) {
        console.log(error); //only string "Not found"
    }
2
  • 1
    angular.io/guide/http#getting-error-details Commented Oct 1, 2018 at 18:53
  • Thanks but there is no information about async/await. or I will have to really use it subscribe, than, catch? Commented Oct 2, 2018 at 14:06

1 Answer 1

1
let response = this.httpClient
 .get( environment.serverUrl + 'api/user/1', { observe: 'response' })
 .toPromise()
 .then( resp => console.log('Success', resp))
 .catch(err => { 
    console.log('Error', err); 
 });
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but I would like to use async/await. or is more used today then, subscribe etc.? what better solution?
If I may suggest, since this is Angular I would recommend using the Observable as is, instead of changing it to a promise. httpClient.get() returns an Observable, which you can use and change it with various rxjs operators. Most of the time I don't subscribe in my component.ts, but in my html template with the async pipe, but before that use the rxjs Map() to format your response as needed. But if you are going to subscribe, don't forget to unsubscribe. this.subscription = response.subscribe( resp => this.values = resp ); And in your onDestroy(): this.subscription.unsubscribe();
Ok, so is it better solution using Observable, subscripe, async pipe instead of async/await? Because it is more beautiful writing, especially when I would like to call more GET methods, I do not have to nest it.
When you need multiple get request which are dependent from each other, you can use operators from rxjs like switchmap, mergemap to combine those streams for your respons output. Creating one observable you subscribe to in your component.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.