2017-01-03 77 views
0

我下面有2用例角2:服務沒有返回值

  1. 獲取產品列表,從JSON文件的教程
  2. 通過使產品獲得點擊的產品的細節ID。

第一部分工作正常。但是,當我點擊一個產品時,服務類沒有返回任何結果。有時,服務類返回值,但其他時間它拋出:

Error: Error in ./ProductDetailComponent class ProductDetailComponent - inline template:31:22 caused by: Cannot read property 'productName' of undefined 
TypeError: Cannot read property 'productName' of undefined 

在調試的問題,我可以看到productId被傳遞到服務層成功。這是一個非常直接的實現,不知道爲什麼它不起作用。 服務類看起來是這樣的:

private url: string = 'api/products/products.json'; 
    private product: IProduct; 
    constructor(private http: Http){} 


    getProducts(): Observable<IProduct[]> { 
    return this.http.get(this.url) 
      .map((response: Response) => <IProduct[]> response.json()) 
      .do(data => console.log('All: '+JSON.stringify(data))) 
      .catch(this.handleError); 
    } 

    getProduct(id: number): Observable<IProduct> { 
    console.log("Id in service class: "+id) 
    return this.getProducts() 
     .map((products: IProduct[]) => products.find(p => p.productId===id)); 
    } 

休息的代碼可以發現here

回答

0

您需要將this.cd.markForCheck();放入ProductDetailComponent的getProduct函數中here;你可能會問,什麼是CD?爲什麼需要cd.markForCheck?請參閱this article

+0

它沒有工作 –

+0

getProduct(ID:數字){ this._productService.getProduct(ID).subscribe( 產物=> {this.product =產物; this.cd.markForCheck();}, 錯誤=> this.errorMessage = 錯誤); } – Timathon

0

看起來你需要使用安全航行運營商在你的模板?.

這是因爲請求的異步特性。

所以在你的模板中,你會改變一些看起來像model.productNamemodel?.productName