Reputation: 6166
I'm learning the ionic framework and want to know how REST calls are done correctly.
I have a RestProvider class which gets me a list of products
rest.ts
getProduct(query: string) {
return this.http.get(searchUri+query)
}
And in my home page I want to assign a value from the response to a local variable
home.ts
ionViewDidLoad() {
this.restProvider.getProduct(query).subscribe(it => {
console.log(it)
this.products = it.result;
})
}
But I get an error on assignment line this.products = it.result;
[ts] Property result does not exist on type Object
How do I create models of my response and assign them to class variables?
Upvotes: 1
Views: 415
Reputation: 7466
The object you get in return is a JSON parsing of the response body. The error is that Typescript does now know if the result
property exists on the returned type. So you should disambiguate the situation.
You declare the type of the returned object with the template argument to get
as in get<MyReturnedType>
. So here, you should provide a template argument containing the result
property.
Either you know the type for it, then use it, or you don't, then use any
and you are responsible for the object accesses you make.
You can get more details on this Angular documentation page.
Note: don't use searchUri+query
as your url because it is not escaped properly. You should instead use HttpParams
described here.
Upvotes: 1