我有一個login()
函數,在我的模板中,有一個綁定到組件的{{message}}
變量。角度2綁定似乎在異步操作後被移除
這裏的登錄功能:
login() {
this.busy = true;
this.message = 'Trying to log in ...'; // correctly updates the template here
this.authService.login().subscribe(
() => {
this.busy = false;
if(!this.authService.isAuthenticated()) {
return;
}
this.router.navigate(['/']);
},
error => {
console.log(this.message);
console.error(error);
this.busy = false;
this.setErrorMessage();
console.log(this.message);
}
);
}
的問題是「錯誤」回調裏面,當我打電話this.setErrorMessage()
,模板沒有得到更新。 我在this.setErrorMessage()
之後做了console.log(this)
,並且組件變量確實設置正確,但它並未反映在HTML中。
任何想法?
更新: 更新了error
函數。也嘗試與.catch()@GünterZöchbauer建議。沒有運氣壽。
這裏的setErrorMessage()
功能:
setErrorMessage() {
this.message = 'There was an error while trying to log you in. Please try again in a few moments!'
}
相關模板部分:
<p id="GB-login-frame-text">
{{message}}
</p>
的authService.login()
函數返回一個Observable
像這樣:
login():Observable<any> {
return this.http.get(API_URL + "/login", {headers: this.headers()})
.map(this.parseResponse)
.catch(this.handleError);
}
的parseResponse
和handleError
個功能:
private parseResponse(response:Response):any {
let result = response.json();
return result.data || {};
}
private handleError(error:any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
if(error.status == 401) {
localStorage.removeItem('user');
window.location.href = '/login';
return;
}
return Observable.throw(errMsg);
}
和控制檯輸出時error
函數被調用:
Trying to log in ...
login.component.ts:39 Object {error: "A generic error occurred"}(anonymous function) @ login.component.ts:39SafeSubscriber.__tryOrUnsub @ Subscriber.ts:240SafeSubscriber.error @ Subscriber.ts:204Subscriber._error @ Subscriber.ts:137Subscriber.error @ Subscriber.ts:107(anonymous function) @ auth.service.ts:50SafeSubscriber.__tryOrUnsub @ Subscriber.ts:240SafeSubscriber.next @ Subscriber.ts:192Subscriber._next @ Subscriber.ts:133Subscriber.next @ Subscriber.ts:93onLoad @ http.umd.js:1104ZoneDelegate.invokeTask @ zone.js:356Zone.runTask @ zone.js:256ZoneTask.invoke @ zone.js:423
login.component.ts:42 There was an error while trying to log you in. Please try again in a few moments!
的message
正在於它似乎組件js
部分正確更新,但它不html
反映。
你能向我們展示了模板和'setErrorMessage'方法? – rinukkusu
完成,但該代碼是非常微不足道的。 –
你可以在Plunker中重現嗎? –