0
votes

I tried to implement CanActivate interface in Angular 6. Below is code snippet

import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate{

  constructor(private authService : AuthService, private router : Router) { }
  canActivate(){
    this.authService.user$.pipe( map( user => {
      if(user) return true;
      this.router.navigate(['/login']);
      return false;
    }));

  }

}

When i do so it throws me following compile time exception

Property 'canActivate' in type 'AuthGuardService' is not assignable to the same property in base type 'CanActivate'. Type '() => void' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | Observable | Promise'. Type 'void' is not assignable to type 'boolean | Observable | Promise'.ts(2416)

I understand above statement, that it required to return one of the following types 'boolean | Observable-boolean | Promise-boolean'

As per my understanding above code returns Observable-boolean. I am just beginner, so not sure when it went wrong.

2

2 Answers

0
votes

Sorry I missed to add return statement as below to the code

  constructor(private authService : AuthService, private router : Router) { }
  canActivate(){
    return this.authService.user$.pipe( map( user => {
      if(user) return true;
      this.router.navigate(['/login']);
      return false;
    }));
0
votes

Change canActivate()

to

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)