Dark Furby
Dark Furby

Reputation: 107

Can i pass outside function to RxJs subscribe?

If i check RxJS subscribe method I can see that:

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

so I write example init function like this:

  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? Can I create function somewhere else and provide it as argument?

for example this function:

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

create in upper class and then provide it as argument.

Ok so I tried to create a method inside a class:

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

}

and tried to pass it to 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?

Upvotes: 0

Views: 260

Answers (1)

MauriceNino
MauriceNino

Reputation: 6747

You need to pass your function without the () or it instantly gets called:

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!')
    )
}
    

Upvotes: 2

Related Questions