Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]
You are returning Observable<Product>
and expecting it to be Product[]
inside subscribe
callback.
The Type returned from http.get()
and getProducts()
should be Observable<Product[]>
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
You have forgotten to mark the getProducts return type as an array. In your getProducts it says that it will return a single product. So change it to this:
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
For those newbies like me, don't assign variable to service response, meaning do
export class ShopComponent implements OnInit {
public productsArray: Product[];
ngOnInit() {
this.productService.getProducts().subscribe(res => {
this.productsArray = res;
});
}
}
Instead of
export class ShopComponent implements OnInit {
public productsArray: Product[];
ngOnInit() {
this.productsArray = this.productService.getProducts().subscribe();
}
}
You must specify which type the response is:
this.productService.getProducts().subscribe(res => {
this.productsArray = res;
});
Try this:
this.productService.getProducts().subscribe((res: Product[]) => {
this.productsArray = res;
});
I had the same problem and I solved as follows define an interface like mine
export class Notification {
id: number;
heading: string;
link: string;
}
and in nofificationService write
allNotifications: Notification[];
//NotificationDetail: Notification;
private notificationsUrl = 'assets/data/notification.json'; // URL to web api
private downloadsUrl = 'assets/data/download.json'; // URL to web api
constructor(private httpClient: HttpClient ) { }
getNotifications(): Observable<Notification[]> {
//return this.allNotifications = this.NotificationDetail.slice(0);
return this.httpClient.get<Notification[]>
(this.notificationsUrl).pipe(map(res => this.allNotifications = res))
}
and in component write
constructor(private notificationService: NotificationService) {
}
ngOnInit() {
/* get Notifications */
this.notificationService.getNotifications().subscribe(data => this.notifications = data);
}