3
votes

i have an issue on CanActivate

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

import { CanActivate } from '@angular/router/src/utils/preactivation';

import { ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { Observable } from 'rxjs';

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']);
        }
    }
}

and it's telling me this :

ERROR in src/app/services/auth-guard.service.ts(10,14): error TS2720: Class 'AuthGuard' incorrectly implements class 'CanActivate'. Did you mean to extend 'Can Activate' and inherit its members as a subclass?
Type 'AuthGuard' is missing the following properties from type 'CanActivate': path, route

But I don't understand why ?

Great thanks to everyone !

3

3 Answers

8
votes

You've imported the CanActivate interface from the wrong place. It should be

import { CanActivate } from '@angular/router';

And it's also a good idea to return false in the else statement.

1
votes

Probably you have strict enabled. Your function specifies return type: Observable<boolean> | Promise<boolean> | boolean, but you are not returning anything from the else branch. Meaning, that your return type is true | undefined or boolean | undefined. You have to return something from the else branch:

import { Observable, EMPTY } from 'rxjs'
// and so on
    canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot )
    : Observable<boolean> | Promise<boolean> |boolean {

        if (this.authService.isAuth) {
            return true;
        }else{
            this.router.navigate(['/auth']);
            return EMPTY;
        }
    }
1
votes

In my case it was a careless mistake where I was providing

        canActivate: AuthGuard,

instead of

        canActivate: [AuthGuard],

Notice the square brackets