【发布时间】: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