2017-10-07 70 views
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; 
} 
+0

它,因为响应是前HTTP异步和方法返回成功变量。帖子。这是因为登录是同步的,并在你内部调用异步函数。您需要登录返回observable,并且您需要订阅此方法才能返回结果 – daremachine

回答

0

您不能混合同步和异步函数来获取结果。

一旦你调用任何异步,你需要等待它,因为它会发生在线程之外。

这将例如

UserService

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 

import { Observable } from 'rxjs/Observable'; 

@Injectable() 
export class UserService { 
    constructor(private http: Http) { } 

    login(username: string, password: string): Observable { 
     return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password })) 
      .map((response: Response) => { 
       if (response.status === 200) { 
        return response.json(); 
       } 
       else { 
        throw new Error('Bad login!'); 
       } 
      }); 
    } 
} 

和其他地方工作,你的组件

@Component({ 
    templateUrl: 'login.component.html' 
}) 
export class LoginComponent { 
    login() { 
     this.userService.login(this.model.username, this.model.password) 
      .subscribe(
       data => { 
        this.router.navigate([this.returnUrl]); 
       }, 
       error => { 
        this.alertService.error(error); 
       }); 
    } 
}