【问题标题】:Angular 7 observable wait for variable to be falseAngular 7 observable 等待变量为假
【发布时间】:2018-12-19 23:18:56
【问题描述】:

以下可观察的:

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

}

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

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

主要思想是调用handleAuth,在内部它应该通过等待局部变量(或发生某些事情)来确保登录不在进行中

【问题讨论】:

  • 贴出局部变量和代码
  • 也许在这个局部变量上使用了setter?
  • 添加了整个代码
  • IMO:我会询问如何在令牌过期时刷新令牌,而不是非常广泛地询问您选择的这种技术解决方案。
  • 为什么不调用函数handleAuth(),在这里设置this.loggingIn = false;

标签: angular typescript promise observable angular7


【解决方案1】:

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

private _localVariable;


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

【讨论】:

  • 我在守卫中调用handleAuth,如果用户当前正在登录,就会出现问题。
【解决方案2】:

您可以做的是将loggingIn 变成Subject,将“完成”事件推送到loggingIn,然后将flatMap loggingIn 推送到http.post

【讨论】:

  • 总之,如果所有异步事件都是Observables,处理异步事件会更容易。
  • 如果需要,我可以提供进一步的解释/代码示例。
  • 我创建了主题:这就是我在登录时将它传送到 http.post .pipe(mergeMap(this.loggingInSubject.asObservable)) 的方式我这样做了 this.loggingInSubject.next(true);并在登录成功/失败时 this.loggingInSubject.next();但我现在得到错误 source.subscribe 不是函数
  • 你需要调用asObservable()作为一个函数。
猜你喜欢
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 2019-09-05
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多