【问题标题】:Angular AuthGuard is not workingAngular AuthGuard 不起作用
【发布时间】:2018-05-19 06:59:44
【问题描述】:

我正在使用角度 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] }
]

我还将它添加到提供者数组中。

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

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

StaticInjectorError(AppModule)[AuthGuard]:
StaticInjectorError(平台:核心)[AuthGuard]:NullInjectorError:否 AuthGuard 的提供者!

我认为我正确地实现了它,但它不起作用。我做错了什么???

【问题讨论】:

  • 尝试将其添加到主模块的提供者
  • 您需要将其添加到模块的providers 部分,在该部分中您使用了使用防护装置的路由配置
  • 另一个问题(与错误无关)是authService.isLoggedIn 是异步的,因此它后面的行将立即执行。所以它总是会重定向到登录
  • 它需要添加到你的模块的 providers 数组中,而不是你的组件中
  • 我已经详细给出了一个答案,提供了您看到错误的原因以及作为解决方案可供您使用的选项 :) 如果您有任何与此问题相关的其他问题或有其他问题问!祝你好运,编码愉快!

标签: angular auth-guard


【解决方案1】:

你应该在 providers 数组中的 app.module 中添加你的守卫名称 像这样的

提供者:[AuthGuard]

【讨论】:

  • 我不认为这是必要的,是吗?
  • 我遇到了同样的问题,虽然我读到的所有内容都说这不应该是必需的,但它确实有效。
  • 只有在某种共享模块中没有提供它或者如果 providedIn: 'root' 没有添加到防护的 Injectable 装饰器时才需要。默认情况下,CLI 不会添加它,因此您必须选择在整个应用程序中如何提供它。
【解决方案2】:

您需要将AuthGuard 包含到app.module.ts 中的提供者数组中

import { AuthGuard } from './_guards/auth.guard'; //<-------

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    LoginComponent,   
  ],
  imports: [   
    MatTableModule,
    EditorModule,    
  ],
  providers: [    
    AuthGuard, // <------------ Include here
    ProfileResolver    
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

【讨论】:

    【解决方案3】:

    在您的 app.module.ts 文件中添加以下内容:

    提供者:[ AuthGuard ]

    【讨论】:

      【解决方案4】:

      您看到的问题是在您的组件中提供了 AuthGuard,但是,它需要在更高级别提供。在您的情况下,路由模块。 staticInjector 错误让您知道 Angular 找不到 AuthGuard。

      正如其他人所提到的,您有两种可用的解决方案。

      选项 1:

      在应用模块或您在模块之间共享的另一个模块中提供您的 AuthGuard。例如,它可能看起来像这样。

      import { NgModule } from '@angular/core';
      import { BrowserModule } from '@angular/platform-browser';
      import { AppRoutingModule } from './app-routing.module';
      import { AppComponent } from './app.component';
      import { AuthGuard } from 'src/app/core/auth.guard';
      
      @NgModule({
        imports: [
          BrowserModule,
          AppRoutingModule,
        ],
        declarations: [
          AppComponent,
        ],
        providers: [
          AuthGuard // ADDED so AuthGuard can be accessed in any routing module.
        ],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
      

      选项 2

      这是我对 AuthGuard 的首选方法,因为它们很可能是 singleton。您只需添加到@Injectable() 装饰器{ providedIn: 'root' }。这看起来像:

      import { Injectable } from '@angular/core';
      import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';
      
      @Injectable({
        providedIn: 'root' // ADDED providedIn root here.
      })
      export class AuthGuard implements CanActivate {
      
      
        constructor() { }
      
        canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
          return true; // AUTH LOGIC HERE.
        }
      
      }
      

      提示:您会注意到,如果您从 CLI 生成服务,它将具有 { providedIn: 'root' },但创建 Guard 不会。

      【讨论】:

        【解决方案5】:

        您应该将AuthGuard 添加到提供程序中的app.module

        Providers:[AuthGuard]
        

        app.module

        import { NgModule } from '@angular/core';
        import { BrowserModule } from '@angular/platform-browser';
        import { AppRoutingModule } from './app-routing.module';
        import { AppComponent } from './app.component';
        import { AuthGuard } from 'src/app/core/auth.guard';
        
        @NgModule({
          imports: [
            BrowserModule,
            AppRoutingModule,
          ],
          declarations: [
            AppComponent,
          ],
          providers: [AuthGuard], // Add AuthGuard here
          bootstrap: [AppComponent]
        })
        export class AppModule { }
        

        【讨论】:

          【解决方案6】:

          添加: { 提供在:“根” } 在 AuthGuard 中的 @Injectable() 内

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-06-20
            • 1970-01-01
            • 1970-01-01
            • 2017-12-13
            • 2018-03-02
            相关资源
            最近更新 更多