Angular 2: How to access an HTTP response body?

后端 未结 10 2039
南方客
南方客 2020-12-13 12:25

I wrote the following code in Angular 2:

this.http.request(\'http://thecatapi.com/api/images/get?format=html&results_per_page=10\').
      subscribe((re         


        
10条回答
  •  Happy的楠姐
    2020-12-13 13:18

    Unfortunately, many of the answers simply indicate how to access the Response’s body as text. By default, the body of the response object is text, not an object as it is passed through a stream.

    What you are looking for is the json() function of the Body object property on the Response object. MDN explains it much better than I:

    The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

    response.json().then(function(data) { console.log(data);});
    

    or using ES6:

    response.json().then((data) => { console.log(data) });
    

    Source: https://developer.mozilla.org/en-US/docs/Web/API/Body/json

    This function returns a Promise by default, but note that this can be easily converted to an Observable for downstream consumption (stream pun not intended but works great).

    Without invoking the json() function, the data, especially when attempting to access the _body property of the Response object, will be returned as text, which is obviously not what you want if you are looking for a deep object (as in an object with properties, or than can’t be simply converted into another objected).

    Example of response objects

提交回复
热议问题