【问题标题】:Getting error while using swichMap operator for nested subscription in angular使用 swichMap 运算符进行角度嵌套订阅时出错
【发布时间】:2021-10-26 06:24:15
【问题描述】:

我得到的错误是

Argument of type '(data: Object) => Observable<Object> | undefined' is not assignable to parameter of type '(value: Object, index: number) => ObservableInput<any>'.
  Type 'Observable<Object> | undefined' is not assignable to type 'ObservableInput<any>'.
    Type 'undefined' is not assignable to type 'ObservableInput<any>'

以下是我遇到问题的代码

  this.AService.aFunction(this.parms).pipe(take(1) ,switchMap( data => {
    if(data){
      return this.aService.bDomain(this.parms)
    }
  })
  ).subscribe(result =>{
    if(result){
      open success modal
    } else {
        open fail modal
    }
  })

【问题讨论】:

  • ... 嗯,有点意思:“好的,在 SwitchMap 内部,您将处理if 条件,继续管道,.. 但是else 怎么样(以防@987654325 @ 语句原来是 false) ..? ..(我的意思是,至少返回 of(null) smt ...)
  • @Vovan_Super 感谢您的帮助。明白了。

标签: angular typescript rxjs


【解决方案1】:

switchMap 需要一个 observable,但你只给它一个 observable if(data){...。所以其他时候它都会失败。

您可以更新switchMap 以始终返回一个可观察的值,或者您可以过滤以仅保留您想要的值并以这种方式忽略错误的data

更新switchMap

this.AService.aFunction(this.parms).pipe(

  take(1),
  switchMap(data => {
    if(!!data){
      return this.aService.bDomain(this.parms)
    } else {
      return EMPTY;
    }
  })

).subscribe(result => {
  if(result){
    open success modal
  } else {
    open fail modal
  }
});

过滤不良data

this.AService.aFunction(this.parms).pipe(

  take(1),
  filter(data => !!data),
  switchMap(data => this.aService.bDomain(this.parms))

).subscribe(result => {
  if(result){
    open success modal
  } else {
    open fail modal
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2019-08-20
    • 2021-05-10
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多