从相反的Angular 2中提取数据

时间:2016-08-02 12:43:16

标签: json angular promise response

我有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'来自这个请求的数组? enter image description here

3 个答案:

答案 0 :(得分: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;
    )};
}

答案 1 :(得分:2)

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

invite.setDeepLink("app_url")

并像这样更改http调用。

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

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

使用此方法,您可以最小化代码大小,否则您必须对每个http调用进行硬编码return this.http.post(this.url + additional_url, {headers: this.headers}) .toPromise() .then(this.extractData) .catch(this.handleError);

答案 2 :(得分:1)

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

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

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