Interface:
export interface Product {
id: number;
name: string;
description: string;
price: number;
imageURL: string;
}
Component:
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
})
}
It throws an error when compiling:
TS2322: Type 'Product[] | null' is not assignable to type 'Product[]'. Type 'null' is not assignable to type 'Product[]'.
How to fix it?
CodePudding user response:
You have
res: HttpResponse<Product[]>
It means that res if of type Product[]. And then you are assigning
this.products = res.body;
where products is of type product array and res is of type Product[]
. Point to note is, Product interface has no body property and hence TS compiler says it can't assign null to products. Try modifying your code like this:
ngOnInit() {
this.dataService.sendGetRequest().pipe(takeUntil(this.destroy$)).subscribe((res)=> {
console.log(res);
this.products = res.body as Product[];
})
}
CodePudding user response:
this.products = res?.body;
or this.products = res.body ? res.body : [];
will simply solve this problem. But better check the API call, actually why it is sending null as res.body
? shouldn't it be an empty array instead?