【问题标题】:How to use combineLatest and takeUntil rxjs operators in Angular 5如何在 Angular 5 中使用 combineLatest 和 takeUntil rxjs 运算符
【发布时间】:2018-03-13 05:58:45
【问题描述】:

我看到在 Angular 5 中应该以不同的方式使用 rxjs 运算符并从 'rxjs/operators' 导入,但我有点不清楚它应该如何工作。我有类似的东西:

import { Observable } from 'rxjs/Observable';

import { combineLatest, takeUntil } from 'rxjs/operators';

@Component({ ... })
export class FooComponent implements OnInit, OnDestroy {


  constructor(private route: ActivatedRoute) {}


  ngOnInit() {

    this.route_data = Observable.combineLatest(this.route.params, this.route.data,
                             (params, data) => ({params,data}));

    this.route_data_sub = this.route_data.takeUntil(this.destroyed$).subscribe(
      (params_and_data) => {
                            ...
                           }
   }
 ...
}

但我收到Observable.combineLatest is not a function 错误。如果我以旧方式添加 combineLatest 运算符,它适用于 combineLatest,但现在找不到 takeUntil。 Angular 5 应该如何做到这一点?

我在整个应用程序中都有相当多的 rxjs 代码,但不知道应该如何重写它或如何更改导入。现在一切都必须用 .pipe() 重写吗?

【问题讨论】:

    标签: angular5 rxjs5


    【解决方案1】:

    你应该导入combileLatest使用

    import { combineLatest } from 'rxjs/observable/combineLatest';

    对于takeUntil

    import { takeUntil } 'rxjs/operators';

    我找到了该信息:

    combineLatest
    takeUntil

    【讨论】:

      【解决方案2】:

      @Mad Dandelion 有正确的答案,但我认为值得展示将它放在一起的样子,以供遇到同一事物的任何人使用。您确实必须通过管道传输诸如 takeUntil 之类的内容。浏览一个大型应用程序并找到所有这些位置有点痛苦,但不会花那么长时间。看起来也不那么糟糕,并且在“为什么”下的 https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md 中具有所有好处。

      import { Observable } from 'rxjs/Observable';
      import { combineLatest } from 'rxjs/observable/combineLatest';
      import { takeUntil } from 'rxjs/operators';
      
      
      @Component({ ... })
      export class FooComponent implements OnInit, OnDestroy {
      
      
        constructor(private route: ActivatedRoute) {}
      
      
        ngOnInit() {
      
          this.route_data = combineLatest(this.route.params,
                                          this.route.data,
                                          (params, data) => ({params,data})
                                         );
      
          this.route_data_sub = this.route_data
                                 .pipe(takeUntil(this.destroyed$)) //<-- pipe()
                                 .subscribe((params_and_data) => {
                                  ...
                                 })
         }
       ...
      }
      

      另外,在我的情况下,我有一些陈旧的 dll 为旧的 rxjs (https://webpack.js.org/plugins/dll-plugin/) 提供服务,所以如果您遇到看起来像您的 Observable 没有管道属性的东西,您可能需要确保 dll 正在构建如果您使用它,请正确使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-25
        • 2018-11-05
        • 2021-01-16
        • 2017-06-25
        • 1970-01-01
        • 2021-02-08
        相关资源
        最近更新 更多