2

I am beginner and learning Angular From tutorials as i follow those tutorials and when i implement interface CanAcivate as he did in tutorial its show error

Class 'AuthGaurd' incorrectly implements interface 'CanActivate'. Property 'canActivate' is missing in type 'AuthGaurd' but required in type 'CanActivate'.ts(2420)

Here is implementation of Canactivate

export class AuthGaurd implements CanActivate
{
  constructor(private auth: AuthService, private router: Router) { }
  CanActivate(){
    return this.auth.user$.map(user => {
      if (user) return true;
      this.router.navigate(['/login']);
      return false;
    });
  }
}`

And here is Imports

 import { Injectable } from '@angular/core';
    import { AuthService } from './auth.service';
    import { CanActivate } from '@angular/router/src/utils/preactivation';
    import { Router } from '@angular/router';
    import 'rxjs/add/operator/map';

I change Import from import { CanActivate } from '@angular/router/src/utils/preactivation'; to import { CanActivate } from '@angular/router; But not work

Also I add following in canActivate as i watch one answer on StackOverflow but it also not work for me

 CanActivate(next: ActivatedRouteSnapshot,
 state: ActivatedRouteSnapshot): Observable<boolean>
Ahmad Raza
  • 758
  • 7
  • 26
  • 5
    The method should be canActivate(). i.e in camelCase. Please refer to https://angular.io/api/router/CanActivate – Vikash B Feb 27 '19 at 07:28

3 Answers3

4

your method should be canActivate() and it should return Observable<boolean> | boolean:

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

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
      this.auth.user$.map(user => {
          if (user) return true;
      this.router.navigate(['/login']);
      return false;
    });
    }
Fateme Fazli
  • 11,582
  • 2
  • 31
  • 48
3

Note the camel case of the canActivate function and use the necessary parameters to implement the function.

Sachin Gupta
  • 4,981
  • 3
  • 16
  • 32
1

You should return a boolean from the canActivate method. There's a spelling mistake in your method. it should be canActivate instead of CanActivate. CanActivate is a interface name where as canActivate is the method name

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot,
     RouterStateSnapshot, Router, CanActivateChild } from '@angular/router';

export class AuthGaurd implements CanActivate
{
  constructor(private auth: AuthService, private router: Router) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){

    this.auth.user$.map(user => {
      if (user) return true ;
      this.router.navigate(['/login']);
      return false;
    });


  }
}
Nithya Rajan
  • 4,722
  • 19
  • 30