javascript - 为什么你会在 Observable 函数上调用 .call() ?

标签 javascript angular rxjs observable ng-bootstrap

我是 Angular 的相对初学者,我正在努力理解我从 ng-bootstrap 项目中阅读的一些源代码。 The source code can be found here .

我对 ngOnInit 中的代码感到很困惑:

ngOnInit(): void {
    const inputValues$ = _do.call(this._valueChanges, value => {
      this._userInput = value;
      if (this.editable) {
        this._onChange(value);
      }
    });
    const results$ = letProto.call(inputValues$, this.ngbTypeahead);
    const processedResults$ = _do.call(results$, () => {
      if (!this.editable) {
        this._onChange(undefined);
      }
    });
    const userInput$ = switchMap.call(this._resubscribeTypeahead, () => processedResults$);
    this._subscription = this._subscribeToUserInput(userInput$);
  }

在这些 Observable 函数上调用 .call(...) 有什么意义?这试图实现什么样的行为?这是正常模式吗?

作为我的 Angular 教育的一部分,我已经阅读/观看了很多关于 Observables 的文章(没有双关语意),但我从未遇到过这样的事情。任何解释将不胜感激

最佳答案

我个人的看法是,他们在 5.5 之前的 RxJS 中使用了它,它引入了可出租运算符。 Angular 在内部使用相同的样式。例如:https://github.com/angular/angular/blob/master/packages/router/src/router_preloader.ts#L91 .

这样做的原因是,默认情况下,他们必须使用 rxjs/add/operators/XXX 修补 Observable 类。这样做的缺点是某些第 3 方库正在修改全局对象,这可能会意外地导致您应用程序中其他地方出现问题。参见 https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md#why .

您可以在文件开头看到他们分别导入了每个运算符https://github.com/ng-bootstrap/ng-bootstrap/blob/master/src/typeahead/typeahead.ts#L22-L25 .

因此,通过使用 .call(),他们可以使用任何运算符,并且仍然避免修补 Observable 类。

关于javascript - 为什么你会在 Observable 函数上调用 .call() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47626326/

相关文章:

angular - 如何在 angular/typescript 中测试私有(private)方法?

javascript - 为什么过滤 observable 订阅的结果会得到与过滤 observable 本身不同的结果

angular - RxJS 更新,属性 'merge' 在类型 'typeof Observable' 上不存在

javascript - 单击按钮后取消订阅的 RXJS 方式,但有机会再次订阅

javascript - 在 JavaScript 中使用 Angular 变量

javascript - 在 Promise 的 then 中返回语句

javascript - 从函数返回的变量在返回后是未定义的

javascript - 通过 javascript 滚动内容时不需要的鼠标事件

angular - 将参数传递给 Angular Directive(指令)

javascript - CSS 未应用于 Pug 条件元素