我遇到問題獲取服務以在頁面上顯示結果。錯誤是訂閱方法返回一個訂閱類型,並且我試圖將其轉換爲產品數組。產品在json文件中。訂閱'不可分配到類型
設置: 我想通過教程學習Angular 2。本教程的日期和我使用的最新版本的角(ng -v = @ angular/cli:1.4.2)。我用ng和ng生成安裝程序。
產品list.component.ts
export class ProductListComponent implements OnInit {
pageTitle = 'Product List';
imageWidth = 50;
imageMargin = 2;
showImage = false;
listFilter = '';
products: IProductList[];
subscription: Subscription;
errorMessage = '';
constructor(private _productListService: ProductListService) {
}
ngOnInit() {
**// ERROR - 'Subscription' is not assignable to type 'IProductList[]'**
this.products = this._productListService.getProducts() // ******** ERROR ******
.subscribe(
products => this.products = products,
error => this.errorMessage = <any>error);
}
產品list.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { IProductList } from './product-list';
@Injectable()
export class ProductListService {
private _productListUrl = 'api/product-list/product-list.json';
constructor(private _http: Http) { }
getProducts(): Observable<IProductList[]> {
return this._http.get(this._productListUrl)
.map((response: Response) => <IProductList[]>response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server Error');
}
}
產品list.component.html
<tr *ngFor='let product of products | async | productFilter: listFilter' >
<td>
<img *ngIf='showImage' [src]='product.imageUrl' [title]='product.productName' [style.width.px]='imageWidth' [style.marging.px]='imageMargin'>
</td>
<td>{{product.productName}}</td>
<td>{{product.productCode | lowercase }}</td>
<td>{{product.releaseDate}}</td>
<td>{{product.price | currency:'USD':true:'1.2-2' }}</td>
<td><app-ai-star [rating] = 'product.starRating'
(ratingClicked)='onRatingClicked($event)'></app-ai-star></td>
</tr>