我遇到的问题与SO Post here中的面孔相同。我在component.ts中的subscribe方法中未定义,即使在我的服务中我有数据。 请参阅以下代码 p.component.ts
private getPayItems():void{
console.log('In getPayItems');
this._payItemService.getPayItems()
.subscribe(data => {
this.payItemArray = data;
console.log(data);
},
(error:any) =>{
this.alerts.push({ msg: error, type: 'danger', closable: true });
})
}
p.service.ts
getPayItems():Observable<Payitem[]>{
let actionUrl = this.url + "/GetPayItem";
return this._http.get(actionUrl, { headers: this.headers })
.map((response: Response) => {
<Payitem[]>response.json() ;
console.log(<Payitem[]>response.json()); //This logs the Object
})
.catch(this.handleError);
}
答案 0 :(得分:5)
当您使用{}
时,它需要从function
显式返回。因此,您必须从<Payitem[]>response.json()
函数返回map
。
getPayItems():Observable<Payitem[]>{
let actionUrl = this.url + "/GetPayItem";
return this._http.get(actionUrl, { headers: this.headers })
.map((response: Response) => {
console.log(<Payitem[]>response.json()); //This logs the Object
return <Payitem[]>response.json() ;
})
.catch(this.handleError);
}
否则以下是简写语法
getPayItems():Observable<Payitem[]>{
let actionUrl = `${this.url}/GetPayItem`;
return this._http.get(actionUrl, { headers: this.headers })
.map((response: Response) => <Payitem[]>response.json())
.catch(this.handleError);
}