ページに結果を表示するサービスを受ける際に問題が発生しました。エラーは、サブスクリプションのメソッドがサブスクリプションの型を返し、製品配列に取得しようとしています。製品はjsonファイルにあります。サブスクリプション 'をタイプに割り当てできません
セットアップ: 私はチュートリアルを進んでAngular 2を学びたいと思っています。このチュートリアルは日付がついており、最新バージョンの角度(ng -v = @ angular/cli:1.4.2)を使用しています。私はng newとng generateを使ってアプリケーションをセットアップしました。
製品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>