0

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?

1 Answer 1

1
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));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but you are combining my two methods into one, this is not what I want.... I know how to do it that way! What do you mean by "checkIfTrue has no return statement"
y => { return y == 1; } is a separate function, it's what I tried to demo with my "a" function. Only this function has a return statement, your checkIfTrue function has no return statement and without a return statement it will not return a value and that's what the compiler error tells you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.