【问题标题】:How to call a function once from Obserable.subscribe regardless if there are data or not in Angular RxJS?无论Angular RxJS中是否有数据,如何从Observable.subscribe调用一次函数?
【发布时间】:2020-03-17 10:13:03
【问题描述】:

有一个从端点获取数据的可观察对象:

this.get().pipe(
  filter(item => item.id = providedId)
).subscribe((data) => {
  specialFunction(data);
})

当 RxJS 的 filter 方法找到一个 item 时,它会触发 subscribe 并且一切都按预期工作。 但是当过滤器找不到项目时,订阅不会被触发。但我也想处理这种情况。我试过用完整的:

this.get().pipe(
  filter(item => item.id = providedId)
).subscribe({
    next: (data) => {
       specialFunction(data);
    },
    complete: (data) => {
       specialFunction();
    }
})

但是,如果存在数据,则 specialFunction 会被调用两次:一次带有数据,一次来自已完成的函数。

如何处理 observable 以便我可以调用一个 specialFunction 一次,无论是否有数据,如果有数据则包含数据?

【问题讨论】:

  • 仅在complete 上处理它并使用if (data) { ... } 启动您的处理程序?
  • 这是一个想法,但是如何从 next 到 complete 很好地传递数据?

标签: javascript angular typescript rxjs frontend


【解决方案1】:

您可以在订阅中过滤您的数据。

this.get().subscribe((data) => {
    const filteredData = data.filter(item => item.id = providedId);
    specialFunction(filteredData);
});


function specialFunction(data: any|undefined) {
    ...
}

【讨论】:

    【解决方案2】:

    您真的不想使用过滤器。使用地图并在订阅中处理匹配:

    this.get().pipe(
      map(item => { isMatch: item.id == providedId, item })
    ).subscribe({
        next: (data) => {
           if (data.isMatch) {
               specialFunction(data.item);
           } else {
              // handle non-match
           }
        },
        complete: (data) => {
           specialFunction();
        }
    })
    

    【讨论】:

    • 谢谢,其实有多个项目可以满足过滤条件。我不知道这是否会这样工作
    【解决方案3】:

    我不明白为什么你不能在 rxjs map 中检查你的条件,如果条件通过则返回真值,否则返回“其他”。但是要放弃另一种选择,您可以...

    也许使用iif:

    根据条件订阅第一个或第二个 observable

    所以也许是这样的:

    import { of, iif } from "rxjs";
    import { mergeMap, filter } from "rxjs/operators";
    
    // ...
    
    this.get()
      .pipe(
        mergeMap(item =>
          iif(() => item.id === providedId
            // if truthy return this
            of(item),
            // if falsy, return null or whatever you like
            of(null)
          )
        )
      )
      .subscribe(data => {
        if (data) {
          specialFunction(data);
        }
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 2019-06-09
      • 2021-07-26
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多