简体   繁体   English

我可以通过 function 外面到 RxJs 订阅吗?

[英]Can i pass outside function to RxJs subscribe?

If i check RxJS subscribe method I can see that:如果我检查 RxJS 订阅方法,我可以看到:

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

so I write example init function like this:所以我这样写示例 init function:

  private init(): void{
this.dataBaseService.fetchPersons().subscribe(
   (persons: Person[]) => {
    this.behaviorSubject.next(persons);
    this.subject.next(persons);
  },
  error => console.error(error),
  () => console.log('Complete!')
);

} }

is it required in Typescript to provide lambda function to argument? Typescript 中是否需要提供 lambda function 到参数? Can I create function somewhere else and provide it as argument?我可以在其他地方创建 function 并将其作为参数提供吗?

for example this function:例如这个 function:

       (persons: Person[]) => {
    this.behaviorSubject.next(persons);
    this.subject.next(persons);
  }

create in upper class and then provide it as argument.在上部 class 中创建,然后将其作为参数提供。

Ok so I tried to create a method inside a class:好的,所以我尝试在 class 中创建一个方法:

  someFunction( persons: Person[] ){
this.behaviorSubject.next(persons);
this.subject.next(persons);

} }

and tried to pass it to init function并试图将其传递给 init function

    private init2(): void {
  this.dataBaseService.fetchPersons().subscribe(
    this.someFunction(),
    error => void,
    () => console.log('Complete!');
  )
}

And I receive error:我收到错误:

An argument for 'persons' was not provided.

What kind of argument I have to provide if its initialisation of this upper method?如果它初始化这个上层方法,我必须提供什么样的论据?

You need to pass your function without the () or it instantly gets called:您需要在没有()的情况下传递您的 function ,否则它会立即被调用:

someFunction( persons: Person[]) {
    this.behaviorSubject.next(persons);
    this.subject.next(persons);
}
    
private init2(): void {
    this.dataBaseService.fetchPersons().subscribe(
        this.someFunction, // <- pass it without ()
        error => void,
        () => console.log('Complete!')
    )
}
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM