简体   繁体   English

RXJS 避免嵌套多个订阅

[英]RXJS avoid nested multiple subscriptions

I would like to transform below code snippet:我想转换下面的代码片段:

 this.dataUserSubscription = this.store$.pipe(select(selectUser)).subscribe(
            user => {
                this.store$.pipe(select(selectUserData, {user}), take(1))
                    .subscribe(userData => {
                        if (userData === null) {
                            this.store$.pipe(select(selectUserManagement, {user}), take(1)).subscribe(
                                userManagement => {
                                    this.store$.dispatch(saveUserDataToStore({
                                        user,
                                        userManagement
                                    }));
                                });
                        }
                    });

by avoid nested subscription.通过避免嵌套订阅。 All examples, which I found, is per two subscriptions.我发现的所有示例都是按两次订阅计算的。

 this.dataUserSubscription = this.store$.pipe(select(selectUser),
    switchMap(user => this.store$.pipe(select(selectUserData, {user}))))
    .subscription(userData => {
        // logic
    })

But it is no proper solution for my example of code.但这不是我的代码示例的正确解决方案。 Why is the proper step for fixing multiple nested subscriptions?为什么修复多个嵌套订阅是正确的步骤?

Per RxJS best practices, your second example is a perfectly acceptable approach.根据 RxJS 最佳实践,您的第二个示例是一种完全可以接受的方法。

But per NgRx best practices, you can get rid of the nested subscription by just combining your selectors.但是根据 NgRx 最佳实践,您可以通过组合选择器来摆脱嵌套订阅。

It's hard to say exactly what to do without seeing your selector files, but if you already have the user in the store, then you should be able to pull the user data out of the store without 2 selector calls.如果没有看到您的selector文件,很难准确地说出该怎么做,但是如果您已经在商店中拥有user ,那么您应该能够在没有 2 次选择器调用的情况下将用户数据从商店中提取出来。

Maybe something like:也许是这样的:

const getDataForUser = createSelector(
    selectUser,
    selectUsers,
    (user, userDataDictionary) => userDataDictionary[user.id]
)

Then just use the one getDataForUser selector.然后只需使用一个getDataForUser选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM