2017-03-08 25 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