Home > OS >  Compilation error in typescript : Function lacks ending return statement and return type does not in
Compilation error in typescript : Function lacks ending return statement and return type does not in

Time:02-02

I have the following typescript function:

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        
        let returnUrl: string = state.url;
        this.authService.redirectUrl =  returnUrl;   
        let loginUrl: string = this.routeService.generateLoginUrl();       

        if( this.authService.isExpiredSession){
            this.authService.refreshToken().subscribe( data =>{
                if (!this.authService.isLoggedIn){
                    this.authService.logout();                 
                    this.router.navigateByUrl(loginUrl);
                    return false;
                }
                else{
                    return true;
                }
            });            
        }
        else{
            return true;
        }      
    }

And the compiler is giving me following error:

Function lacks ending return statement and return type does not include 'undefined'.

It seems to me that all code paths are covered. Am I missing something?

Thanks for any insight on this.

CodePudding user response:

The return in the subscribe call just return the next call of the subscribe method, it does not actually return the function. So, your function needs to return an observable of boolean.

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
        
        let returnUrl: string = state.url;
        this.authService.redirectUrl =  returnUrl;   
        let loginUrl: string = this.routeService.generateLoginUrl();       

        if( this.authService.isExpiredSession){
            return this.authService.refreshToken().pipe( 
                map(data =>{
                    if (!this.authService.isLoggedIn){
                        this.authService.logout();                 
                        this.router.navigateByUrl(loginUrl);
                        return false;
                    }
                    else{
                        return true;
                    }
                })
            );            
        }
        else{
            return of(true);
        }      
    }

Angular behind the scenes subscribes to the returned Observable and uses the streamed value to decide the result.

I suggest watching Decoded Frontend on youtube to get better at angular and RxJS

  • Related