如何在嵌套的Observables中返回一个Observable?

问题描述 投票:0回答:1

我有两个嵌套的observable,第一个observable提供了一个ID,它作为参数传递给第二个可观察的userTypeID

目标是返回一个基于actionType的Observable,它可以是viewedit,以便做这样的事情。

// returns view object 
getPresentationFields('view').subscribe(data => console.log(data)); 

// returns edit object
getPresentationFields('edit').subscribe(data => console.log(data)); 

但是,由于我已经订阅了getPresentationFields(...)中的Observables,我无法按照上面的说明订阅该函数。

getPresentationFields(actionType: string) {
    this.customerService.getUserByID(this.id).subscribe(user => {
        this.presConfigService.getPresConfig(user.userTypeID).pipe(
            flatMap((configs) => configs),          // ----[obj1, obj2, obj3]----
            filter((configs) => configs.show)      // ----obj1----obj2----obj3----
        ).subscribe(() => {
            if(actionType == 'view'){
                // Return View Observable
            }else if(actionType == 'edit'){
                // Return Edit Observable
            }
        });
    });
}

如何根据传递给getPresentationFields('view')getPresentationFields('edit')的参数返回一个Observable?

angular rxjs observer-pattern
1个回答
2
投票

您不需要订阅getPresentationFields代码,只需通过Observable。

粗略的例子(不确定您需要返回哪个配置部分进行查看/编辑)

function getPresentationFields(actionType: string) {
  return this.customerService
    .getUserByID(this.id)
    .pipe(
      switchMap(user => this.presConfigService.getPresConfig(user.userTypeID)),
      flatMap((configs) => configs),
      filter((configs) => {
        if(actionType == 'view'){
          return configs.show;
        }else if(actionType == 'edit'){
          return configs.edit;
        }
      })
    )
}

或者你可以在某处更高的if-else:

function getPresentationFields(actionType: string) {
  const result$ = this.customerService
    .getUserByID(this.id)
    .pipe(
      switchMap(user => this.presConfigService.getPresConfig(user.userTypeID))
    );

 if(actionType == 'view'){
    return result$.pipe(
      // ... get view data
    );
  } else if(actionType == 'edit'){
    return result$.pipe(
      // ... get edit data
    )
  }
}

通常,只需在使用结果的位置订阅Observable。

甚至可能会发生你实际上没有在你的代码中订阅,而是在外面的某个地方传递observable,比如使用angular | asyncredux effects

因此,大多数情况下,您将使用switchMapmergeMapcombineLatest等运算符来处理您的数据并将其传递给订阅,订阅将变得尽可能薄。

© www.soinside.com 2019 - 2024. All rights reserved.