Angular2 http获取数据到localstorage不起作用

时间:2017-03-08 14:45:59

标签: angular

我最近开始研究角度2,我现在正在试用http部分,但是我遇到了一些问题。

当我点击按钮激活该功能时,http.get会向php发送一个密码用户名和密码。

http接收详细信息(此部分有效),并且假设将数据存储在localstorage中,但这不起作用,只有当我再次点击时才能工作。

我做错了什么?

HTML

<input type="text" [(ngModel)]="username" /><br>
<input type="text" [(ngModel)]="password" /><br>
<button (click)="checkLogin()">set</button>

Angular2功能

checkLogin() {
    let url = 'http://localhost:82/api/getData.php?key=' + this.key + '&username=' + this.username + '&password=' + this.password;
        this.http.get(url)
        .subscribe(res => this.userData = res.json());

    let jsonId = this.userData['id'];
    let jsonUsername = this.userData['username'];

    localStorage.setItem('id', jsonId);
    localStorage.setItem('username', jsonUsername);

    // error handling
    let jsonError = this.userData['error'];

    localStorage.setItem('error', jsonError);
}

1 个答案:

答案 0 :(得分:1)

您应该确保在设置之前收到所需的响应。尝试这样的事情:

checkLogin() {
    let url = 'http://localhost:82/api/getData.php?key=' + this.key + '&username=' + this.username + '&password=' + this.password;
        this.http.get(url)
        .subscribe(res => {
            this.userData = res.json();

            //for readability you should export this part in a local function
            let jsonId = this.userData['id'];
            let jsonUsername = this.userData['username'];

            localStorage.setItem('id', jsonId);
            localStorage.setItem('username', jsonUsername);

            // error handling
            let jsonError = this.userData['error'];

            localStorage.setItem('error', jsonError);
        });
}