简体   繁体   English

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

[英]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. 在局部变量为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'. 我读到应该使用Promises和await运算符进行异步函数调用来完成此操作,但是我找不到可以轮询变量值的东西,只能“等待一段时间并解决”。

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

You can use a setter on the local variable for this purpose : 为此,可以在局部变量上使用setter:

private _localVariable;


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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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