I have this Product interface:
export interface Product{
code: string;
description: string;
type: string;
}
Service with method calling product endpoint:
public getProducts(): Observable<Product> {
return this.http.get<Product>(`api/products/v1/`);
}
And component where I use this service to get the Products.
export class ShopComponent implements OnInit {
public productsArray: Product[];
ngOnInit() {
this.productService.getProducts().subscribe(res => {
this.productsArray = res;
});
}
}
With this state I'm getting error:
[ts] 型 'Product' には、型 'Product[]' の以下のプロパティがありません: length、pop、push、concat、その他 26 個。[2740]
変数の型指定を削除するとproductsArray
エラーはなくなりますが、サーバーの応答がProducts
?型のオブジェクトの配列であるため、これが機能しない理由がわかりません。
ベストアンサー1
戻ってきてObservable<Product>
、それがコールバックProduct[]
内に入ることを期待していますsubscribe
。
返される型http.get()
はgetProducts()
Observable<Product[]>
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}