2016-11-22 207 views
1

我遇到的挑戰與SO中的面孔相同here我在component.ts的訂閱方法中未定義,即使在我的服務中我有數據。 請參見下面的代碼 p.component.tsAngular 2可觀察訂閱顯示undefined

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

回答

5

當你使用{}它需要function明確的回報。所以你必須從map函數返回<Payitem[]>response.json()

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

你剛纔救了我的一天,先生!謝謝 –