pmeyer
pmeyer

Reputation: 890

Typescript Nested Observables

Background: Using rxjs Observables

I'm trying to call a method (with an observable) that calls another method. This current setup isn't working for me with the following compilation error in checkIfTrue function in service 1...

A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)

//component
//makes call to service
process = () => {
     this.service1.checkIfTrue().subscribe(x => {console.log(x)});
};

//service 1
//makes call to service 2
checkIfTrue = (): Observable<boolean> => {
     this.service2.getInt().subscribe(y => { return y == 1;});
};


//service 2
//makes call to service 2
getInt = (): Observable<number> => {
     return Observable.of(1);
};

It seems like I can't return the response from the second method...How can I achieve this?

Upvotes: 0

Views: 248

Answers (1)

Christoph L&#252;tjen
Christoph L&#252;tjen

Reputation: 5924

checIfTrue (): Observable<boolean> => {
     this.service2.getInt().subscribe(y => { return y == 1;});
};

You have two functions here:

  • checkIfTrue()
  • y => { return y == 1; }

Your second function has a return statement, your checkIfTrue() has no return statement. That's why it does not return a value. Just as an example, that should make clear why that cannot work:

// y => y == 1 function dummy
function a() {
  return true;
}

// subscribe() dummy
function b(callback: Function) {
  callback();
}

function checkIfTrue() {
  // your subscribe(y => y == 1) line
  b(a);
}

What you're looking for is something like this

checIfTrue (): Observable<boolean> => {
   return this.service2.getInt()
    .pipe(map(y => y == 1));
};

You can shorten this as:

checIfTrue (): Observable<boolean> => this.service2
    .getInt()
    .pipe(map(y => y == 1));

Upvotes: 1

Related Questions