简体   繁体   English

如何将HTTP JSON响应转换为HTML(Ionic2,Angular2,TypeScript,PHP,JSON)?

[英]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.. 我目前正在开发我的第一个Ionic 2应用程序,但我还不太喜欢打字稿。

I want to call the authenticate() method in my constructor and afterwards to 我想在我的构造函数中调用authenticate()方法,之后调用

  1. get the whole JSON response into the textarea and/or 将整个JSON响应放入textarea和/或
  2. access the username and password value of the json response in my HTML 访问我的HTML中的json响应的用户名和密码值

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: 我已从API获得的响应:

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

HTML: HTML:

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

--> textarea is empty - > textarea是空的

You would want to extract the object that is inside the array, which is inside Person : 您可能希望提取数组内部的对象,该对象位于Person

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

Furthermore, you need to assign the data to this.data like so: 此外,您需要将数据分配给this.data如下所示:

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

Then use (together with the safe navigation operator ? here.) 然后使用(连同安全导航操作员 ?在这里。)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM