javascript - 订阅 onComplete 永远不会用 flatMap 完成

标签 javascript angular typescript rxjs rxjs6

我将 Angular 6RxJS 6.2.2RxJS Compact 6.2.2 一起使用。

我有一个代码可以调用我的 api 服务来加载一些记录,它是:

this.route.params
  .flatMap((params: Params) => {
    if (!params['id']) {
      return Observable.throwError('Id is not specified.');
    }

    this.itemId = params['id'];
    this.isEditMode = true;
    this.loadCategoryGroupCondition = new LoadCategoryGroupViewModel();
    this.loadCategoryGroupCondition.id = [this.itemId];
    this.loadCategoryGroupCondition.pagination = new Pagination();

    return this.categoryGroupService
      .loadCategoryGroup(this.loadCategoryGroupCondition);
  })
  .subscribe(
    (loadCategoryGroupResult: SearchResult<CategoryGroup>) => {
      console.log(loadCategoryGroupResult);
    },
    () => {},
    () => {
      console.log('Completed')
    });

上面的代码可以打印从我的 api 服务返回的我的项目列表。这意味着 onSuccess 已被调用。

但是完整的方法被触发了。 我的代码有什么问题?

谢谢,

最佳答案

如前所述,flatMap 运算符本身并不完成其源可观察性。您正在使用 this.route.params 作为源可观察对象,它是长期存在的 - 它永远不会自行完成。

要获得完成 通知,您可以使用诸如take 之类的运算符。它将重新发出您作为参数传递的项目数,然后完成。例如,如果您只想接收当前路由并且对源可观察对象的进一步通知不感兴趣,请使用 take(1),例如:

this.route.params
  .take(1)
  .flatMap((params: Params) => {

此外,请注意,在 RxJS 6+ 中推荐的执行此操作的方法是使用可管道运算符。这看起来像这样:

this.route.params.pipe(
  first(),
  mergeMap((params: Params) => {
  ...
})

我还用更新的推荐变体替换了运算符。

关于javascript - 订阅 onComplete 永远不会用 flatMap 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52464729/

相关文章:

javascript - 将给定 div 中的每个字母放在单独的范围内

Javascript,设计函数来引用自身

Javascript 字符串到数组/字典

angular - 如何监听 MSAL-Angular token 重新身份验证请求?

angular - 黄金布局 Angular 2+/ng-golden-layout

angular - 在初始化时隐藏 TinyMce 工具栏

javascript - 在 $scope.$watch 中调用一个函数

linux - CentOS7如何保留程序?

typescript - ‘serviceBusTrigger’, 'signalR' 绑定(bind)类型突然未注册

typescript - TS2322 : Type 'string' is not assignable to type '"union"| "of" | "strings"'