简体   繁体   中英

Angular 7 observable wait for variable to be false

The following observable:

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;
}

}

should not be executed until a local variable is false.

I read that this should be done using Promises and async function call with await operator, but I could not find something that will poll for the variable value, only 'wait for some time and the resolve'.

The main idea is to call handleAuth and internally it should assure that login is not in progress, by waiting for the local variable (or something to happen)

You can use a setter on the local variable for this purpose :

private _localVariable;


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

您可以做的是使loggingInSubject ,将“ done”事件推送到loggingIn ,然后将flatMap loggingIn送到http.post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM