0

Goal: If the server response with 200 code, I want to perform some changes on the record locally.

issue: I am not able to access the response code or the 'message' attribute

this is how the server response from this http call::

// MongooseModelSchema: this is the model that uses moongose 
    MongooseModelSchema.updateOne({ _id: req.params.id, creator: req.userData.userId }, channel)
      .then(result => {
        if (result.n > 0) {
          res.status(200).json({ message: "Update successful!" }); // this is what I want to capture
        } else {
          res.status(401).json({ message: "Not authorized!" });
        }
      })
      .catch(error => {
        console.log(error);
        res.status(500).json({
          message: "Couldn't udpate channel!"
        });
      });

I am able to hit the API no problem

I have the following http snip in my angular code::

    this.http
      .put(BACKEND_URL+'setState/' + id, channelData)
      .subscribe(response => {
        console.log('response',response);
        console.log('check if response has Update successful!: ',JSON.stringify(response).search('Update successful!'));
        console.log('response.message',response.message);

       this.router.navigate(["/editChannel", id]);
      })

this is the console.log image: consolelog image

issue image: as you can see, i dont have access to the return code. I also cant access the 'message' property UNTIL i run the code, then it works.... super weird.

error on message property

How do I check for the 200 code?

Juan Casas
  • 268
  • 2
  • 13
  • you can check this for status code: https://stackoverflow.com/questions/43683052/get-status-code-http-get-response-angular2 – Jimmy Dec 26 '22 at 20:49

1 Answers1

1

That makes sense. Message object is not typed, so compiler is telling you that message doesn't exist on response. Instead what you should do is the following:

myresponse.ts:

interface MyResponse {
 message: string
}

this.http
      .put<MyResponse>(BACKEND_URL+'setState/' + id, channelData)
      .subscribe(response => {
        console.log('response',response);
        console.log('check if response has Update successful!: ',JSON.stringify(response).search('Update successful!'));
        console.log('response.message',response.message);

       this.router.navigate(["/editChannel", id]);
      })

now angular will grab the response and map it to the MyResponse interface giving you ability to access the message property. Alternatively you could keep it as any or unknown not sure what the type on response by default is, but if its any just do response['message']

Hope that helps.

O.MeeKoh
  • 1,976
  • 3
  • 24
  • 53