dzitrus dzitrus - 1 month ago 11
TypeScript Question

How to get HTTP JSON-response into HTML (Ionic2, Angular2, TypeScript, PHP, JSON)?

I am currently working on my first Ionic 2 app, but I am not yet very much into typescript..

I want to call the authenticate() method in my constructor and afterwards to


  1. get the whole JSON response into the textarea
    and/or

  2. access the username and password value of the json response in my HTML



TypeScript:

export class WelcomePage {
public data: string;
username: string;
password: string;

constructor(public navCtrl: NavController, public http: Http) {
this.authenticate();
}

authenticate() {
var creds = { username: 'user1', password: 'pw1' };

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');

this.http.post('http://www.xyz.api.php', creds, {
headers: headers
})
.map(res => res.json())

.subscribe(
data => this.data,
err => this.logError(err),
() => console.log('Completed')
);
}
}


Response I already got from API:

{ "Person":[ {"Username":"user1","Password":"pw1"} ] }


HTML:

<textarea>here: {{data}}</textarea>


--> textarea is empty

Answer

You would want to extract the object that is inside the array, which is inside Person:

.map(res => res.json().Person[0]) // extract object

Furthermore, you need to assign the data to this.data like so:

.subscribe(
   data => this.data = data // here!
   ....

Then use (together with the safe navigation operator ? here.)

{{data?.Username}} and {{data?.Password}}