Angular 2 个可观察订阅显示未定义

Angular 2 observable-subscribe showing undefined

我面临着与 SO Post 中相同的挑战 我在 component.ts 的订阅方法中未定义,即使在我的服务中我有数据。 请参阅下面的代码 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);
}

当您使用 {} 时,它需要来自 function 的显式 return。所以你必须 return <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);
}

否则下面将是shorthand语法

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);
}