0
votes

I'm trying to return the current authentication status in a service method. (The code works except for the return.) I'm not familiar with the call to .then inside .map and I can't figure out how to return an Observable.

public getSignedInStatus(): Observable<boolean> {
        this._gauth.getAuth().map(auth => {
            auth.then(function() {
                return Observable.of(auth.isSignedIn.get());
            });
        });
    }

In the docs, there's a subscribe call. I tried changing it to .map but it didn't help.

this._gauth.getAuth()
        .subscribe(auth => {

The error is "A function whose declared type is neither 'void' nor 'any' must return a value."

I want to be able to call the method from any component. Something like this:

return this._userService.getSignedInStatus()
      .map(
        signedIn => {    
          if (signedIn === true) {
            return true;
          } else {
            return false;
          }
        },
        error => console.error('Error getting user status')
      );

And in an AuthGuard, like this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this._userService.getSignedInStatus()
    .subscribe( response => {
        const status = response.isSignedIn.get();
        if (status === true) {
           return true;
        } else {
           this.router.navigate(['/signin']);
           return false;
        }
    },
    error => {
       console.error('Error getting user status');
       return false;
    });
  }
}
1
There are some issue with your code . What is the return type of this._gauth.getAuth() ? if the return value of public getSignedInStatus(): is Observable<boolean> then you need to use subscribe() in your component class to consume the service like return this._userService.getSignedInStatus() .subscribe(Niladri
Thanks. the return type is Observable<gapi.auth2.GoogleAuth>. But getSignedInStatus() won't build, so I haven't gotten to the call from the component yet.beachCode
what is the error you are getting currently when using map?Niladri
@Niladri the error is in the question. The return is not valid. The error is "A function whose declared type is neither 'void' nor 'any' must return a value."beachCode

1 Answers

1
votes

Something like this should work

public getSignedInStatus(): Observable<gapi.auth2.GoogleAuth> {
    return this._gauth.getAuth();
}

And in your route guard you subscribe to the observable and you return it

return this._userService.getSignedInStatus()
  .subscribe( response => {    
      return response.isSignedIn.get();
  },
  error => {
     return false
  });