0

i have a login page and 3 more pages along with that. Now i need to do authentication function. If the authentication is undefined then it must redirected to login page, if authentication is true it must go to checkLogin function. I am not getting how to do this but i had tried in this way,in one of the pages.

ts:

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

@Injectable()
export class PageComponent implements CanActivate {

    constructor(private router: Router) { }

    canActivate() {
      if (localStorage.getItem('authToken') == undefined ) {
        this.router.navigate(['/login']);
      }
      else {
            /*Checklogin*/    
        this.ApiService
            .checklogin()
            .subscribe(
              user  => {}
      }
        }

but i get an error:

Class 'PageComponent' incorrectly implements interface 'CanActivate'.
  Types of property 'canActivate' are incompatible.
    Type '() => void' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | Observable<boolean> | Pr...'.
      Type 'void' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.

I dont know what i am doing is correct or not, can anyone guide me

Bhrungarajni
  • 2,415
  • 11
  • 44
  • 88

2 Answers2

0

You have to return boolean or Observable<boolean> or Promise<boolean> from canActivate

Also

canActivate should be something like this

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    //Your logic
}

Example

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    if (localStorage.getItem('authToken') == undefined ) {
        return false; 
    }
  else {    
    return new Observable<boolean>((observer)=>{
        this.ApiService
        .checklogin()
        .subscribe((res)=>{
           //Check user
           if(condition){
              observer.next(true);
           }
           else{
             observer.next(false);
           }
           observer.complete();
        });
   });
  }

}
Deepak Kumar T P
  • 1,076
  • 10
  • 20
0

CanActivate route guard expect a boolean, Observable or a Promise to be returned. Based on the value returned the page is authenticated.

In your case you can probably do something like this.

canActivate() {
  if (localStorage.getItem('authToken') == undefined ) {
    return false;
  }
  else {  
         return this.ApiService.checklogin()
      }
    }

In the implementation of checklogin you resolve/reject you promise/observable.

You can go through following article: https://ryanchenkie.com/angular-authentication-using-route-guards

Amal
  • 278
  • 1
  • 11