Angular 从服务触发事件并等待所有订阅者 return 一个值

Angular trigger event from service and wait for all subscribers to return a value

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

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

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 模块中创建一个侦听器列表,其他所有人都会将他们的承诺添加到该列表中,而 auth 模块只会等待所有这些承诺完成...

由于订阅者作业是异步的,您必须了解这些作业并等待它们发出 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 仅发出一个值并完成。