界面:
export interface Product {
id: number;
name: string;
description: string;
price: number;
imageURL: string;
}
成分:
products: Product[] = [];
ngOnInit() {
this.dataService.sendGetRequest().pipe(takeUntil(this.destroy$)).subscribe((res: HttpResponse<Product[]>)=>{
console.log(res);
this.products = res.body; // The error is in this place
})
}
編譯的時候報錯:
TS2322: Type 'Product[] | null' is not assignable to type 'Product[]'. Type 'null' is not assignable to type 'Product[]'.
如何解決?
uj5u.com熱心網友回復:
你有
res: HttpResponse<Product[]>
這意味著 res if 型別為 Product[]。然后你正在分配
this.products = res.body;
其中 products 是 product array 型別, res 是 type Product[]。需要注意的是,Product 介面沒有 body 屬性,因此 TS 編譯器說它不能為產品分配 null。嘗試像這樣修改你的代碼:
ngOnInit() {
this.dataService.sendGetRequest().pipe(takeUntil(this.destroy$)).subscribe((res)=> {
console.log(res);
this.products = res.body as Product[];
})
}
uj5u.com熱心網友回復:
this.products = res?.body;或this.products = res.body ? res.body : [];將簡單地解決這個問題。但最好檢查一下 API 呼叫,實際上為什么它發送 null as res.body?它不應該是一個空陣列嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335766.html
