我下面有2用例角2:服務沒有返回值
- 獲取產品列表,從JSON文件的教程
- 通過使產品獲得點擊的產品的細節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。
它沒有工作 –
getProduct(ID:數字){ this._productService.getProduct(ID).subscribe( 產物=> {this.product =產物; this.cd.markForCheck();}, 錯誤=> this.errorMessage =錯誤); } –
Timathon