【问题标题】:Extract data from respone Angular 2从响应 Angular 2 中提取数据
【发布时间】:2016-12-07 19:49:52
【问题描述】:

我有 1 个组件和 1 个服务。

组件元素:

...
constructor(private requestService : RequestService)
{

}
ngOnInit()
{
    this.a = this.requestService.send_request(urlWebAPI);
    console.log(this.a);
}
...

服务:

constructor(private http: Http) 
{
    this.http = http; 
    this.headers = new Headers
    ({
        'Content-Type': 'application/json'
    });
}

send_request(additional_url: String) 
{       
    return this.http.post(this.url + additional_url, {headers: this.headers})
        .toPromise()
        .then(response => response.json())
        .catch(this.handleError);
}
private handleError(error: any) 
{
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
}

但这就是我打印的内容...如何从该请求中直接提取“listaUniversita”数组?

【问题讨论】:

    标签: json angular promise response


    【解决方案1】:

    在您的 ngOnInit 中获取返回的承诺,如下所示:

    ngOnInit()
    {
        this.requestService.send_request(urlWebAPI).then((result) => { 
        console.log(result);
        )};
    }
    

    Console.log 将显示从服务器返回的内容。即 console.log(result.listaUniversita)

    【讨论】:

      【解决方案2】:
      send_request(additional_url: String) 
      {       
          return this.http.post(this.url + additional_url, {headers: this.headers})
              .toPromise()
              .then(response => response.json().data)                    //<----changed it
              .catch(this.handleError);
      }
      
      
      ngOnInit()
      {
          this.requestService.send_request(urlWebAPI).then((result) => {  //<----changed it
             this.a=result;
          )};
      }
      

      【讨论】:

      • 后来当我打印“a”时它仍然是“未定义”
      • 是的,我只需要更改“数据”字段...ty!
      【解决方案3】:

      您可以将新方法调用 extractData 添加到服务中,它应该是这样的。

      private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
      }
      

      并像这样更改 http 调用。

      return this.http.post(this.url + additional_url, {headers: this.headers})
          .toPromise()
          .then(this.extractData)
          .catch(this.handleError);
      

      参考https://angular.io/docs/ts/latest/guide/server-communication.html

      使用此方法,您可以最小化代码大小,否则您必须在每次 http 调用时硬编码 response =&gt; response.json().data

      【讨论】:

      • this.extractData 方法有时会出错并且不会给出预期的结果。相反,当硬编码 response => response.json().data 它确实给出了我想要的。有什么想法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      • 2023-03-04
      • 2022-01-22
      • 2017-05-30
      • 1970-01-01
      相关资源
      最近更新 更多