Angular 2: How to access an HTTP response body?

后端 未结 10 2021
南方客
南方客 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条回答
  • 2020-12-13 13:00
    .subscribe(data => {   
                console.log(data);
                let body:string = JSON.parse(data['_body']);`
    
    0 讨论(0)
  • 2020-12-13 13:03

    Here is an example to access response body using angular2 built in Response

    import { Injectable } from '@angular/core';
    import {Http,Response} from '@angular/http';
    
    @Injectable()
    export class SampleService {
      constructor(private http:Http) { }
    
      getData(){
    
        this.http.get(url)
       .map((res:Response) => (
           res.json() //Convert response to JSON
           //OR
           res.text() //Convert response to a string
       ))
       .subscribe(data => {console.log(data)})
    
      }
    }
    
    0 讨论(0)
  • 2020-12-13 13:03

    The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().

      this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
      .map(res => res.json())
      .subscribe(data => {
        console.log(data);
      })
    

    https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data

    0 讨论(0)
  • 2020-12-13 13:07

    This should work. You can get body using response.json() if its a json response.

       this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
          subscribe((res: Response.json()) => {
            console.log(res);
          })
    
    0 讨论(0)
  • 2020-12-13 13:08

    Both Request and Response extend Body. To get the contents, use the text() method.

    this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10')
        .subscribe(response => console.log(response.text()))
    

    That API was deprecated in Angular 5. The new HttpResponse<T> class instead has a .body() method. With a {responseType: 'text'} that should return a String.

    0 讨论(0)
  • 2020-12-13 13:09

    Can't you just refer to the _body object directly? Apparently it doesn't return any errors if used this way.

    this.http.get('https://thecatapi.com/api/images/get?format=html&results_per_page=10')
                .map(res => res)
                .subscribe(res => {
                    this.data = res._body;
                });
    

    Working plunker

    0 讨论(0)
提交回复
热议问题