2

I have a problem when I use CanActivate method: error ts2366 "Function lacks ending return statement and return type does not include undefined" appears.

Following my code:

import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) { }

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

I tried to add '| undefined' after boolean but an other error told me it was incompatible with CanActivate.

Do you have any idea to solve it ?

Thanks by advance for your help.

  • You are supposed to return either a `boolean` or a `UrlTree` from `canActivate`. If you return the UrlTree it will deal with the navigation for you, so you don't need to call `this.router.navigate` yourself (see https://angular.io/api/router/CanActivate) – cdimitroulas Apr 14 '21 at 13:59
  • @cdimitroulas So, if I understand, I need to return a ```this.router.parseUrl('/auth')``` in the second case and the navigate will be automaticaly done with this UrlTree ? – thomas rocheteau Apr 14 '21 at 14:11
  • I believe so - I haven't actually worked with Angular so I'm basing this off what is written in the docs link I sent in my previous comment. – cdimitroulas Apr 14 '21 at 14:25
  • @cdimitroulas thanks for your answer, it is solved. – thomas rocheteau Apr 14 '21 at 14:57
  • I'm going to add a proper answer to your question - if you could mark it as the correct answer I would appreciate it :) – cdimitroulas Apr 14 '21 at 16:10

1 Answers1

3

You are supposed to return either a boolean or a UrlTree from canActivate. If you return the UrlTree it will deal with the navigation for you, so you don't need to call this.router.navigate yourself (see https://angular.io/api/router/CanActivate)

Your code might look like this:

import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuth) {
      return true;
    } else {
      return this.router.parseUrl('/auth');
    }
  }
}
cdimitroulas
  • 2,380
  • 1
  • 15
  • 22