首页 文章

Angular AuthGuard不起作用

提问于
浏览
0

我使用角度CanActivate Authguard接口来保护我的组件 .

@Injectable()
export class AuthGuard implements CanActivate{

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

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {

    this.authService.isLoggedIn.take(1).map((isLoggedIn : boolean) => {

        if(!isLoggedIn){
            this.router.navigate(['/login']);
            return false;
        }

        return true;
    })

    this.router.navigate(['/login']);
    return false;
   }
}

我把它添加到我的路由器配置中 .

const appRoutes: Routes = [
{path : '',redirectTo : 'login',pathMatch : 'full'},
{ path: 'home', component: HomeComponent,canActivate : [AuthGuard] }
]

我还将它添加到providers数组中 .

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [AuthGuard,  
ExpenseService,SellDetailService,AuthenticationService],
styleUrls: ['./app.component.css']
})

但是,当我运行应用程序时,它给出了以下错误

StaticInjectorError(AppModule)[AuthGuard]:StaticInjectorError(Platform:core)[AuthGuard]:NullInjectorError:没有AuthGuard的提供者!

我认为我是以正确的方式实施的,但它不起作用 . 我做错了什么???

1 回答

  • 1

    你应该将你的警卫的名字添加到provider数组中的app.module这样的东西

    提供商:[AuthGuard]

相关问题