我有一個簡單的方法,使一個POST請求Angular2第一響應於POST請求未定義
postData(){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var json = JSON.stringify({email: 'Admin', password: 'Admin'});
return this._http.post('http://localhost:8080/addressbook_rest/api/v1/contacts/login', json ,
{headers: headers});
}
然後從另一個分量I調用上述方法
onLogin() {
this._service.postData().map(res => res.json()).subscribe(
data => { this.loggedin = data },
err => { console.log(err); }
);
console.log(this.loggedin);
}
的問題是,在第一調用,這個變量this.loggedin是未定義的,但之後,我得到了我想要的(this.loggedin = true)。我不知道爲什麼它只能從第二次獲得它。
但我需要在一個IF中POST後的this.loggedin。我應該怎麼做才能讓這個郵件的價值在那裏?如果(!this.loggedin){this.errorMsg ='登錄失敗';} – mlhack
要解決您的第一個問題,您可以將'loggedIn'屬性初始化爲'false'。否則,你需要異步思考你的應用程序。我不知道你的代碼,但我會看到這樣的:'this._service.login(this.user).subscribe(loggedIn => {if(!loggedIn){this.errorMsg ='無法登錄' ;}});'看看我的意思? –