为什么routing.module文件中的防护程序阻止了所有路由?,

时间:2019-07-14 22:13:42

标签: angular routing guard

如果我将提供程序的数组添加到admin-routing.module,则无法打开此模块中定义的任何路由,但仅将canActivate规则添加至仅一个子路径。

如果我在admin-routing.module中清理提供程序,那么我可以访问管理路由,但我选择的带有防护功能的路径除外。但是AuthGuard不能正常工作-不要导航到固定路径(这很明显-我没有注册服务,所以角度看不到-我认为是这样的。))。

如果我在admin.module.ts中注册AuthGuard,则整个应用程序将无法运行。我没有尝试在任何地方注册任何其他防护(在app-routing.module.ts中没有提供者)。

这是admin-routing.module.ts:

const adminRoutes: Routes = [
  {
    path: "",
    component: AdminPanelComponent,
    children: [
      { path: "", redirectTo: "login", pathMatch: "full" },
      {
        path: "manage",
        component: ManageArticlesComponent,
        canActivate: [AuthGuard],
        children: [
          {
            path: "create",
            component: CreateArticleComponent
          },
          {
            path: "articles",
            component: ArticleListComponent
          }
        ]
      },
      {
        path: "login",
        component: LoginComponent
      },
      {
        path: "signup",
        component: SignupComponent
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(adminRoutes)],
  exports: [RouterModule],
  providers: [AuthGuard]
})

这是我的AuthGuard:

export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}
  //method canActivate gets params: actual route and state. We always take it from this router objects as below.
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    // return true;
    if (this.authService.isAuth()) {
      return true;
    } else {
      this.router.navigate(["/admin/login"]);
      return false;
    }
    //isAuth method added to if statement returns true or false depends on is user logged in or registered in.
    //it need to return true or promise /(or) observable that resolve to true. in other case gets error.
  }
}

预先感谢任何想法,是什么导致了我的问题。

0 个答案:

没有答案