angularobservableangular2-routingangular2-services

Route Guard - observable


    import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { Observable } from "rxjs";

import { AuthService } from './auth.service';

@Injectable()


export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService, private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
            this.authService.isAuthenticated()
            .then(
                (authenticated: boolean) => {
                    if (authenticated) {
                        return true;
                    }else{
                        this.router.navigate(['/']);
                        
                    }
                }
            );
            
        }

    
}

I keep getting the error

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

15 state: RouterStateSnapshot): Observable | Promise | boolean{

this code is taken a from a tutorial i am working with, tired a bunch of stuff including a return false; at the end still gives the same error. any ideas ?

thanks


Solution

  • In your example, you need to return the Promise resulting from the then(...) method and make sure that inside the then(...) you always return a boolean, like this:

    canActivate(route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
                return this.authService.isAuthenticated()
                .then(
                    (authenticated: boolean) => {
                        if (authenticated) {
                            return true;
                        }else{
                        this.router.navigate(['/']);
                            return false;
                        }
                    }
                );
                
            }
    

    And instead of this.router.navigate(...) it would be better to return a UrlTree in your promise and use it to change the location (documentation here: https://angular.io/api/router/CanActivate).