Angular 7可观察的等待变量为false

时间:2018-12-19 15:00:23

标签: angular typescript promise observable angular7

以下可观察到的:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthService {
    readonly loginUrl = <login_url>;
    readonly authStatusUrl = <auth_status_url>;
constructor(private http: HttpClient, private cookieService: CookieService) {}

loggingIn = false;

login(username: string, password: string) {
    this.loggingIn = true;
    const creds = {
        username: username,
        password: password
    };
    this.http
    .post<any>(this.loginUrl, creds, {})
    .subscribe(
        data => this.onLoginSuccess(data),
        error => this.onLoginFail(error));
}

handleAuth(): Observable<any> {

    const token = this.cookieService.get('token');
    const refresh = this.cookieService.get('refresh');

    // should wait for loggingIn to be false
    return this.http
        .post<any>(this.authStatusUrl, { }, {
            headers: {
                token: token,
                refresh: refresh
            }
        });
}

public onLoginSuccess(data) {
    this.loggingIn = false;
    this.cookieService.set('token', data.access_token);
    this.cookieService.set('refresh', data.refresh_token);
}

onLoginFail(err) {
    console.log('Faild to login');
    this.loggingIn = false;
}

}

在局部变量为false之前不应执行。

我读到,这应该使用Promises和await运算符的异步函数调用来完成,但是我找不到可以轮询变量值的东西,只能“等待一段时间并解决”。

主要思想是调用handleAuth,并在内部通过等待局部变量(或发生的事情)来确保登录未在进行中

2 个答案:

答案 0 :(得分:0)

为此,您可以在局部变量上使用setter:

private _localVariable;


set localVariable(value) {
  this._localVariable = value;
  if(this._localVariable) {
   //call your function here.
  }
}

答案 1 :(得分:0)

您可以做的是将loggingIn设为Subject,将“ done”事件推送到loggingIn,然后将flatMap loggingIn放入{{ 1}}。