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

Cod*_*ein 8 javascript observable rxjs ng-bootstrap angular

我是Angular的初学者,我正在努力理解我从ng-bootstrap项目中读取的一些来源.源代码可以在这里找到.

我对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$);
  }
Run Code Online (Sandbox Code Playgroud)

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

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

Tin*_*ang 1

为了理解它,首先你可以看一下预定义的 JavaScript 函数方法“call”:

var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
person.fullName.call(myObject);  // Will return "Mary Doe"
Run Code Online (Sandbox Code Playgroud)

调用“call”的原因是调用对象“person”中的函数并将上下文传递给它“myObject”。

同样,这个调用“call”的原因如下:

const inputValues$ = _do.call(this._valueChanges, value => {
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
});
Run Code Online (Sandbox Code Playgroud)

提供上下文“this._valueChanges”,同时还提供基于该上下文调用的函数,即第二个参数,匿名函数

value => {
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
}
Run Code Online (Sandbox Code Playgroud)

在您使用的示例中:

  • this._valueChanges 是可观察的输入事件

  • _do.call 用于在事件输入发生时执行一些副作用,然后返回源 Observable(事件 observable)的镜像 Observable

更新的 示例代码:https://plnkr.co/edit/dJNRNI ?p=preview

关于do调用:

你可以像这样在 Observable 上调用它:

const source = Rx.Observable.of(1,2,3,4,5);
const example = source
.do(val => console.log(`BEFORE MAP: ${val}`))
.map(val => val + 10)
.do(val => console.log(`AFTER MAP: ${val}`));
const subscribe = example.subscribe(val => console.log(val));
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您不必将第一个参数作为上下文“Observable”传递。

但是,当您像您所说的那样从自己的位置调用它时,您需要将第一个参数作为您想要调用的“Observable”传递。这就是不同之处。

正如@Fan Cheung提到的,如果你不想从自己的地方调用它,你可以这样做:

const inputValues$=this._valueChanges.do(value=>{
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
})
Run Code Online (Sandbox Code Playgroud)