-2

我有 2 个返回 Observables 的函数,我想一个接一个地执行。 函数1返回

Observable<SomeDataObject> 

function2返回类型

Observable<Any>

我希望执行它们的函数根据 function1 的结果返回布尔 我在运行第一个function1时设法这样做了,但现在我想先运行function2,我得到了错误:

"Argument of type '(res: <SomeDataObject>) => boolean' is not assignable to 
 parameter of type '(value:SomeDataObject, index: number) => 
ObservableInput<any>. Type 'boolean' is not assignable to type 
ObservableInput<SomeDataObject>

查看我的代码:这有效

return this.someService.function1().pipe(
  switchMap(f1Result => 
  {
     this.someService.repositpry.f1ResultData = f1Result;
     return this.someService.function2().pipe(
        map(res => 
       {
           if (res) return true;
           else return false;
       }));
   })
 ) 

失败了

 return this.someService.function2.pipe( 
  switchMap(f2Result => 
  {
      this.someService.function1().pipe(
       map(f1result => 
       {
           this.someService.repositpry.f1ResultData = f1Result;
       })
    );
    if (f2Result) return true
    else return false;
 }));

解决方案:

return this.someService.function2().pipe( 
  switchMap(f2Result => 
  {
      return this.someService.function1().pipe(
       map((f1result) => 
       {
           this.someService.repositpry.f1ResultData = f1Result;
           if (f2Result) return true
           else return false;
       })
    );

 }));
4

3 回答 3

1

在您的第二个示例中,在最外部的管道中,您有

this.someService.function1().pipe(
       map(f1result => 
       {
           this.someService.repositpry.f1ResultData = f1Result;
       })

f1result是一个可观察的。在内部管道中,您使用map运算符。这与第一个示例不同,它正在工作,因为在第一个示例中您使用switchMap,它会使 Observable 变平。

因此,您可能还必须switchMap在内部管道中使用,然后使用 amap返回您正在寻找的结果,就像这样

return this.someService.function2.pipe( 
  switchMap(f2Result => 
  {
      this.someService.function1().pipe(
       switchMap(f1result => 
       {
           this.someService.repositpry.f1ResultData = f1Result;
       }.pipe(() => {
           if (f2Result) return true
           else return false;
       }))
    );
 }));

没有真实的例子可以尝试,这只是一个建议

于 2020-03-04T09:59:59.470 回答
1

嗨,您需要一个 concatMap 运算符来执行此操作。

return this.someService.function1().pipe(
  concatMap(f1Result => 
  {
     this.someService.repositpry.f1ResultData = f1Result;
     return this.someService.function2.pipe(
        map(res => 
       {
           if (res) return true;
           else return false;
       }));
   })
 ) 
于 2020-03-04T10:23:34.067 回答
1

你应该认真处理你的问题。另请阅读: https ://stackoverflow.com/help/how-to-ask

你做:

this.someService.function2.pipe(
  //...
)

不应该是:

this.someService.function2().pipe(
  //...
);

没有看到你function1function2人不能帮助你。

于 2020-03-04T09:51:24.377 回答