I get the following error in Angular when I try to copy the result of the
http service into variable products. Any ideas please? I think this might
be related to the mapping, which I'm unsure how to do.
Btw I want to use HttpClient, not Http, and the mapping should be done
automatically by using the get<type>("api/route"); syntax, right?
Error TS2322 (TS) Type 'Observable<Product[]>' is not assignable to
type 'Product[]'. Property 'includes' is missing in type
'Observable<Product[]>'.
Here is the code:
import { HttpClient} from "@angular/common/http"
import { Injectable } from "@angular/core"
import { Product } from "./product";
import { Observable } from "rxjs";
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
public products: Product[] = [];
loadProducts(): Observable<Product[]> {
debugger;
this.products = this.http.get<Product[]>("/api/products");
return true;
}
}
The previous version, that worked, without typesafety, is (just for the
record):
...
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
public products = [];
loadProducts() {
return this.http.get("/api/products")
.map((data: any[]) => {
this.products = data;
return true;
});
}
}
I am interested to make the example with type safety work, for this of
course Product is defined in a .ts file like this:
export interface Product {
id: number;
category: string;
size: string;
//...
}
and I made sure the properties returned from the api match the properties
from the interface.
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.