簡體   English   中英

Angular 7可觀察的等待變量為false

[英]Angular 7 observable wait for variable to be false

以下可觀察到:

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,並在內部通過等待局部變量(或發生的事情)來確保登錄未在進行中

為此,可以在局部變量上使用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