猿问

我可以将外部函数传递给 RxJs 订阅吗?

如果我检查 RxJS 订阅方法,我可以看到:


    subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;

所以我写了这样的示例初始化函数:


  private init(): void{

this.dataBaseService.fetchPersons().subscribe(

   (persons: Person[]) => {

    this.behaviorSubject.next(persons);

    this.subject.next(persons);

  },

  error => console.error(error),

  () => console.log('Complete!')

);

}


Typescript 是否需要为参数提供 lambda 函数?我可以在其他地方创建函数并将其作为参数提供吗?


例如这个功能:


       (persons: Person[]) => {

    this.behaviorSubject.next(persons);

    this.subject.next(persons);

  }

在上层创建,然后将其作为参数提供。


好的,所以我尝试在类中创建一个方法:


  someFunction( persons: Person[] ){

this.behaviorSubject.next(persons);

this.subject.next(persons);

}


并试图将它传递给 init 函数


    private init2(): void {

  this.dataBaseService.fetchPersons().subscribe(

    this.someFunction(),

    error => void,

    () => console.log('Complete!');

  )

}

我收到错误:


An argument for 'persons' was not provided.

如果它初始化这个上层方法,我必须提供什么样的论据?


心有法竹
浏览 142回答 1
1回答

长风秋雁

你需要在没有的情况下传递你的函数,()否则它会立即被调用:someFunction( persons: Person[]) {&nbsp; &nbsp; this.behaviorSubject.next(persons);&nbsp; &nbsp; this.subject.next(persons);}&nbsp; &nbsp;&nbsp;private init2(): void {&nbsp; &nbsp; this.dataBaseService.fetchPersons().subscribe(&nbsp; &nbsp; &nbsp; &nbsp; this.someFunction, // <- pass it without ()&nbsp; &nbsp; &nbsp; &nbsp; error => void,&nbsp; &nbsp; &nbsp; &nbsp; () => console.log('Complete!')&nbsp; &nbsp; )}&nbsp; &nbsp;&nbsp;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答