2017-10-07 71 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); 
       }); 
    } 
}