【问题标题】:Angular trigger event from service and wait for all subscribers to return a value来自服务的角度触发事件并等待所有订阅者返回一个值
【发布时间】:2021-01-16 06:27:49
【问题描述】:

我有一个身份验证模块,它使用oidc-client 作为基础...
我想在用户登录后加载一些关于用户的初始数据......但是由于这些信息与其他模块相关并且将来可能会发生变化,所以我不想在身份验证服务本身中进行硬编码......

所以我想在加载用户时触发事件......

public onUserLoading: BehaviorSubject<User> = new BehaviorSubject(this.user);

    this._userManager    = new UserManager(this._getClientSettings());
    this.userLoadPromise = this._userManager.getUser();
    this.userLoadPromise.then(user => {
      this.user       = user;
      this.onUserLoading.next(user);
      //wait for the onUserLoading event to finish before setting this.userLoaded value
      this.userLoaded = true;
    });

但是我需要等待onUserLoading 的所有订阅者完成后才能继续执行下一行代码,但我不知道怎么做!!!

或者有没有更好的方法?

我最后的选择是在 auth 模块中创建一个侦听器列表,其他人会将他们的 Promise 添加到该列表中,而 auth 模块只会等待所有这些 Promise 完成......

【问题讨论】:

  • “我需要等待所有订阅者完成 onUserLoading”是什么意思。这些需要完成的过程是同步还是异步?如果它们是同步的,您可以使用 take(1) 订阅 onUserLoading 并在获取值时覆盖 userLoaded 标志。但是,我认为不需要,因为当您发出时,所有订阅者都会在下一行之前获得价值,因为他们将在下一行之前进入事件循环。
  • @BrunoJoão 它们是异步 http 调用,需要从至少 2 个不同的 api 端点加载有关用户的信息
  • 在这种情况下,您必须知道这些调用并等待它们。订阅者不可能告诉主题他们已经处理了该值而不告诉它需要等待什么。为此,您使用 switchMap 顺序调用每个 http 或使用 forkJoin 同时调用所有这些。 userManager.getUser().then(res => forkJoin([call1, call2, call3]).pipe(take(1)).subscribe(([res1, res2, res3]) => this.userLoaded = true; ));。告诉我这是否有意义,以便我可以将其写为答案。
  • @BrunoJoão 是的,这就是我的想法,tnx

标签: angular events openid-connect


【解决方案1】:

由于订阅者作业是异步的,因此您必须知道这些作业并等待它们发出 userLoaded。

订阅者不可能告诉主题他们已经处理了该值而不告诉它需要等待什么。

为此,您可以使用 switchMap 顺序调用每个 http 或使用 forkJoin 来同时调用所有这些。

userManager.getUser()
    .then(res => forkJoin([call1, call2,call3])
        .pipe(take(1))
        .subscribe(([res1, res2, res3]) => this.userLoaded = true)
    );

take(1) 用于确保取消订阅所有订阅者。当“接收到”一个值时,此运算符完成。参数是在完成流之前要“接收”的值的数量。例如, take(3) 将接收 3 个值并完成。

如果您只进行 http 调用,则可以删除 take(1),因为 HttpCliente 只发出一个值并完成。

【讨论】:

  • tnx,1 个问题,take(1) 到底是做什么的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 2010-11-17
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多