skip to Main Content

i’m new in Angluar ! and i’m trying to parse a reponse inside an angular service

this.httpClient.get(this.url+formula).subscribe(response => {
      this.response = response
    });

reponse should be something like that :

Object { code: 200, formula: "2", result: 2, status: "Success" }

i’m getting an error when i’m tring to get the status, result or code : this.code not working

 error TS2339: Property 'code' does not exist on type 'Object'.

I will be very grateful for your help

2

Answers


  1. The issue here is that typescript cant infer what kind of object you are getting from the request, so using dot notation myObject.someProperty wont work because typescript does not recognize someProperty. You need to explicitly let typescript know the type of object you are getting, something like this:

    this.httpClient.get<MyResponseType>(this.url+formula).subscribe(
        // Here typescript already knows the type of the response
        response => console.log(response.code) // works fine
    )
    

    Alternatively you can try accessing the property using bracket notation:

    this.httpClient.get(this.url+formula).subscribe(
        response => console.log(response['code']) // also works but doesnt provide autocomplete
    )
    
    Login or Signup to reply.
  2. I believe you have to specifically tell the Angular HttpClient that you want to access the whole response (and not just the body) when you make the http request. Could you try the following:

    this.httpClient.get<any>(this.url+formula, { observe: 'response' }).subscribe((response: HttpResponse<any>) => {
      this.response = response;
      console.log(response.code);
    });
    

    Note that you can change the to a more appropriate type, namely the type of object that this endpoint should return in the response body.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search