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