【发布时间】:2019-07-31 06:21:53
【问题描述】:
我在 Angular 6 应用程序 (app.routing.ts) 中创建了一个路由模块。我在我的应用程序中添加了多个路由,但没有在任何地方使用child 指令作为我的路由(是的不好的做法,但是现在我在我的应用程序的另一部分添加了动态路由并且不想更改整个结构,因为这样做需要很长时间)。
我想知道是否有一种方法可以全局使用canActivate: [AuthGuardService](检查用户是否已登录)用于除根以外的所有路由。我检查了一个类似的答案here,但警卫似乎无法正常工作并且仍然加载页面。 (也许是因为我没有任何子路线)。
另外,我认为该方法也可能不是最好的方法,因为在这种情况下,Guard(消费层)能够知道哪个层正在使用它的方法(这不是 mvc 模式的最佳方法,授予我对路由模块所做的事情也不漂亮)。有没有办法以更清洁的方式实现这一目标?
app.routing.ts
export const routes: Routes = [
{
path: 'main',
component: MainComponent,
pathMatch: 'full'
},
{
path: 'search/:id',
component: GlobalSearchComponent
},
{
path: '',
canActivate: [AuthGuardService],
component: LoginComponent,
},
{
path: 'reset',
component: ResetPasswordComponent
},
{
path: 'forgot',
component: ForgotPasswordComponent
},
{
path: 'knowledge-base/create',
component: KnowledgeBaseCreateComponent
},
{
path: 'knowledge-base/detail/:id',
component: KnowledgeBaseDetailComponent
},
{
path: 'knowledge-base/edit/:id',
component: KnowledgeBaseEditComponent
},
{
path: 'projects/detail/:id',
component: ProjectDetailComponent
},
{
path: 'projects/create',
component: ProjectCreateComponent
},
{
path: '**',
component: NotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
authguard.service
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
/**
* This injector provides the auth-guard service throughout the application.
*/
@Injectable({
providedIn: 'root'
})
/**
* The auth guard service is used to prevent unauthenticated users from
* accessing restricted routes, it's used in app.routing.ts to protect the home
* page route
*/
export class AuthGuardService {
/**
* The constructor initializes the ToastrService & TranslatePipe in the component.
*/
constructor(private toastr: ToastrService,
private translate: TranslatePipe,
private router: Router) { }
/**
* This method checks if the user is authorized to access a certain route.
*
* @param route
* @param state
* @return
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('jwtToken')) {
return true;
} else {
if (this.router.url !== '/') {
let error = this.translate.transform("generic[responses][error][401]");
this.toastr.warning(error);
this.router.navigate(['']);
} else {
return true;
}
}
}
}
【问题讨论】:
标签: angular typescript angular-router angular-router-guards