2017-03-08 26 views
0

我最近开始研究angular 2,现在我尝试了http部分,但是我遇到了一些问题。Angular2 http获取数据到localstorage不起作用

当我点击按钮来激活该功能时,http.get会发送一个用户名和密码的密钥给我在php中制作的api。

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); 
} 
+0

这是一个异步问题,您正尝试在最有可能设置值之前分配到本地存储。检查我的答案在这里:http://stackoverflow.com/a/42654240/6294072 – Alex

回答

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); 
     }); 
} 
+0

谢谢,这固定它。 – kaaai3

+0

不客气;) – mickdev