Angular 5 Service正在从api返回数据,但Component没有向我显示数据

时间:2017-12-01 00:01:58

标签: javascript angular rxjs observable

Angular 5中的大部分内容与typescript和带有observables的rxjs非常类似于angular 2,4,但我似乎无法理解为什么我的组件代码没有显示数据。

这是我的代码

模特:

export class arsCodes {
  iD: number;   
  aRSCode: string;
  aRSDescription: string;
  class: string;
  victimFlag: string;
  startDate: string;
  endDate: string;
  createdByUserID: string;
  createdOnDateTime: string;
  modifiedByUserID: string;
  modifiedOnDateTime: string;
}

工作服务

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

getArsCodesApi(search: arsCodes) {
  return this.http.post(this.serviceUrl, JSON.stringify(search), httpOptions)
    .map((response: Response) => {
      response;
      console.log(response) // WORKS
    })
}

上面的console.log中的“响应”返回{Status:“success”,Message:“”,data:Array(16)}

然后

 data: Array(16) 
 >0: {ID: 4443, ..... }  
 //etc.. 

但是,我在订阅中的Component文件中调用它是未定义

arsCode: ArsCode[];

this.arsSevice.getArsCodesApi(this.model).subscribe(
  result => {
    //this.arsCode = result
    console.log(result);
  },
  error => {
    console.log(error);
  }
)

我的组件需要做什么来检索数据?

2 个答案:

答案 0 :(得分:2)

问题是您没有在服务的.map()函数中返回任何内容(不需要使用HttpClient)

但无论如何,你必须这样回来:

return this.http.post(this.serviceUrl, JSON.stringify(search), httpOptions)
  .map((response: Response) => {
    console.log(response);
    return response;
  });

答案 1 :(得分:1)

您正在返回地图功能。在您的http请愿书中包含此代码以返回数据:

return this.http.post(this.serviceUrl, JSON.stringify(search), httpOptions)
    .map(this.extractData)
    .catch(this.handleError);

从普通数据中提取是一个简单的回报:

private extractData(res: Response): Observable<any> {
    return res|| { };
  }

对JSON数据使用return res.json 。您也可以将其用于错误控制:

 private handleError(error: any){
    return Observable.throw("Data unavailable or incorrect url");
  }