1

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?

3
  • check if 'it' contains a result property, if so check r u accessing that in a valid way Commented Nov 12, 2018 at 10:57
  • 'it' is a JSON response and 'it.result' isn't explicitly defined anywhere, how can I do that? Commented Nov 12, 2018 at 11:05
  • 1
    That'll be because of Typescript. Change the service to this.http.get<any>(searchUri+query) and it should work. Better yet, if you have an interface that represents the response, use that instead of any Commented Nov 12, 2018 at 11:09

1 Answer 1

1

The object you get in return is a JSON parsing of the response body. The error is that Typescript does now know if the resultproperty 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.