我最近開始研究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);
}
這是一個異步問題,您正嘗試在最有可能設置值之前分配到本地存儲。檢查我的答案在這裏:http://stackoverflow.com/a/42654240/6294072 – Alex