且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当用户在浏览器选项卡中手动更改url时,防止在Angular中进行路由

更新时间:2023-08-25 11:04:58

现在是2018年! Angular 5在这里,解决此问题的方法也是如此. BAMM的 CanActivate 接口,类可以实现此接口,以作为确定是否可以激活路由的后卫.

Its 2018! Angular 5 is here and so is the solution to this issue. BAMM its CanActivate Interface that a class can implement to be a guard deciding if a route can be activated.

我们可以添加此功能,并根据我们定义的条件阻止访问某些路线.可以将实现CanActivate接口并定义canActivate方法的AuthGuard等服务添加到路由配置中.

We can add this functionality and prevent the access to some of our routes based on the conditions we define. A service for eg AuthGuard that implements the CanActivate interface and defines the canActivate method can be added to route configuration.

class Permissions {
  canGoToRoute(user: UserToken, id: string): boolean {
    return true;
  }
}

@Injectable()
class AuthGuard implements CanActivate {
  constructor(private permissions: Permissions, private currentUser: UserToken) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return this.permissions.canGoToRoute(this.currentUser, route.params.id);
  }
}

如果我们有一条要防止某些情况下访问的路由,则按如下所示添加防护:

If we have a route that we want to protect access to against some condition, we add the guard as follows:

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  {
    path: 'heroes',
    canActivate: [AuthGuard],
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

这里的路线heroes及其所有子项在其上都有一层保护层.因此,根据AuthGuard服务返回的布尔值,将允许或拒绝用户访问此路由.

Here the route heroes and all its children have a layer of guard over it. Hence based on the boolean value returned by the AuthGuard service the user will be allowed or denied access to this route.