0
因此,我試圖在訂閱observable後,在成功函數回調中更改變量'success'。在爲其編寫測試之後,我使用Chrome調試器進行了調試,並且未能在成功的POST中返回true。Angular Observables在訂閱內更改本地函數變量onSuccess => {}
測試進入響應=> {}函數,但在逐步執行「success = true」之後,它仍然是錯誤的。因爲我將爲其他各種函數做這件事,所以我希望有一長串的類變量,以便像我在其他例子中看到的那樣用「this」來引用它們。有沒有辦法讓成功成爲現實?
public login(username: string, password: string): boolean {
let success = false;
this.http.post<LoginResponse>('/api/login_check', {username: username, password: password}).subscribe(
response => {
success = true;
this.currentUser = new User(response.user);
sessionStorage.setItem('userJWT', response.token);
},
error => {
console.log('Login failed - ' + error);
}
);
return success;
}
它,因爲響應是前HTTP異步和方法返回成功變量。帖子。這是因爲登錄是同步的,並在你內部調用異步函數。您需要登錄返回observable,並且您需要訂閱此方法才能返回結果 – daremachine