简体   繁体   中英

Ts Error : A function whose declared type is neither 'void' nor 'any' must return a value. when return statements are inside a subscribe method

I've made a simple service in my Angular 2 project for checking if the user is logged in or not. It checks if the user object exists within the FirebaseAuth object. But the function declaration throws an error for the "lack of return statement" when actually my return statements are inside the subscribe method on the auth variable. Code looks something like this:

import { Component, OnInit , Injectable} from '@angular/core';
import { FirebaseAuthState, FirebaseAuth} from "angularfire2";
@Injectable()
export class CheckLogged {

constructor(private auth:FirebaseAuth ){}
check(): boolean{
    this.auth.subscribe((user: FirebaseAuthState) => {
        if (user) {
            return true;  
        }
        return false;
    })
  }
}

The "check():boolean" statement throws this error

Im calling my function inside an OnInit lifecycle hook in a component and assigning it to a variable

this.loggedIn = this.CheckLogged.check();
  check(): boolean{ // <<<== no boolean is returned from this function
    this.auth.subscribe((user: FirebaseAuthState) => {
        if (user) {
            return true;  
        }
        return false;
    })
  }

In above code return xxx only returns from the callback passed to subscribe(...) , but doesn't return from check .

You can't switch from async back to sync. The method should look like

  check(): Observable<boolean>{ // <<<== no boolean is returned from this function
    return this.auth.map((user: FirebaseAuthState) => {
        if (user) {
            return true;  
        }
        return false;
    })
  }

and then the caller needs to subscribe to the return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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