Ravi Bhartiya
Ravi Bhartiya

Reputation: 299

angular subscribe data json value

I am using Angular 5 and my below function is posting the data to the server

doLogin(){
  var link = 'https://www.sportsmanager.us/Ionic/ASPPages/IonicRMLogin.asp?Login=T&O=2';
  var myData = JSON.stringify({txtEmailAddress: this.txtEmailAddress,txtPassword:this.txtPassword});
  this.http.post(link, myData)
       .subscribe(data => {
      alert(data['code'])
   }, error => {
     alert("Oooops!");
  });


}

and server return the json in following formart

{"code":"0","msg":"The email address entered is not assigned to any adult coaches. Please try a different email address or contact your administrator for assistance.", "page":"IonicRMHome.asp"}

when I try to get code value through data['code']. I get undefined error.

Upvotes: 1

Views: 8232

Answers (4)

ranakrunal9
ranakrunal9

Reputation: 13558

As per your error message it seems like you have passed wrong email address to API but if your email address is correct then you can try to check with below code as there is no need to use JSON.stringify if your API accept Content-type: application/json:

doLogin() {
  const link = 'https://www.sportsmanager.us/Ionic/ASPPages/IonicRMLogin.asp?Login=T&O=2';

  const myData = {
    txtEmailAddress: this.txtEmailAddress,
    txtPassword: this.txtPassword
  };

  this.http.post(link, myData).subscribe(data => {
    console.log(data);
  }, error => {
   alert("Oooops!");
  });
}

if your API do not accept Content-type: application/json then you have to add header in your POST API call as below :

this.http.post(link, myData, {
  headers: new HttpHeaders().set('Content-type', 'Content type accepted by API'),
}).subscribe(data => {
  console.log(data);
}, error => {
  alert("Oooops!");
});

Upvotes: 0

Ravi Bhartiya
Ravi Bhartiya

Reputation: 299

I was able to get it done by doing it in following way :

let dataJSON = JSON.parse(data["_body"]);

Upvotes: 0

Wasif Khan
Wasif Khan

Reputation: 954

Just do console.log(data) and you will get to see why it is giving error.

As my guess is that it is a json response, and it has data.detail.code.

Upvotes: 1

Ram_T
Ram_T

Reputation: 8484

Data from server always comes as string. So, please parse it before using

Try

  this.http.post(link, myData)
       .subscribe(data => {
       data = JSON.parse(data);
      alert(data['code'])
   }, error => {
     alert("Oooops!");
  });

Upvotes: 1

Related Questions