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

Vis*_*ati 10 angular-ui-router angular2-routing angular

当用户在浏览器选项卡中手动更改路径并按Enter键时,我遇到了问题.这迫使我的ui-router/angular2-router导航到用户输入的状态.我想阻止这种情况,并且只允许通过我在网站上点击按钮实现的流程进行路由.

Sco*_*eed 10

您可以在守卫的构造函数中导入路由器。此路由器实例将具有当前 URL。canActivate 中的 ActivatedRouteSnapshot 和 RouterStateSnapshot 将包含用户尝试访问的 URL。

下面的示例阻止用户从外部页面直接访问路由。

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class DirectAccessGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    // If the previous URL was blank, then the user is directly accessing this page
    if (this.router.url === '/') {
      this.router.navigate(['']); // Navigate away to some other page
      return false;
    }
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

将此防护添加到您的路由模块

{ path: 'signup/:type/:step', component: SignupComponent, canActivate: [DirectAccessGuard] }
Run Code Online (Sandbox Code Playgroud)

  • 我这里遇到了僵局 (3认同)

Vis*_*ati 9

它的2018年!Angular 5就在这里,这个问题的解决方案也是如此.BAMM它的CanActivate接口,类可以实现作为一个保护决定路由是否可以激活.

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我们有一个我们希望保护访问某些条件的路由,我们按如下方式添加保护:

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 }
];
Run Code Online (Sandbox Code Playgroud)

这条路线heroes及其所有孩子都有一层防守.因此,基于AuthGuard服务返回的布尔值,将允许或拒绝用户访问此路由.

  • 如何检测导航是由手动 url 更改还是内部路由器导航方法触发的? (4认同)

小智 5

似乎是一个老问题,但我也被困在这里,直到我得到一个适合我的应用程序的东西。

您可以采取以下措施来阻止直接浏览器 url 操作:

1) 在整个应用程序中导出静态布尔字段。假设它是 Helper.isNextStep(将文件另存为 helper.ts)。

export class Helper {
static isNextStep: boolean; }
Run Code Online (Sandbox Code Playgroud)

2) 在页面视图上将此静态字段设置为 false (在 app.component.ts 构造函数中轻松完成),如下所示:

  import {Helper} from '../path/to/helper.ts' 

  export class AppComponent {
  constructor() {
  location.onPopState(() => {

    Helper.isNextStep = false;

    })
 }}
Run Code Online (Sandbox Code Playgroud)

3) 设置 canActivate 防护,如下所示:

import { Helper } from '../path/to/helper.ts'
import { CanActivate } from '@angular/router/router';
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(public zone: NgZone, public router: Router) {

}
canActivate(): boolean {
if (!Helper.isNextStep) {
  this.zone.run(() => {
    this.router.navigate(['']) //you can redirect user to any page here ( Optional )
  })
  return false;  //block navigation
}
else {
  return Helper.isNextStep || true;  // allow navigation
}
}
Run Code Online (Sandbox Code Playgroud)

4)在app.module.ts中提供这个canActivate守卫

providers: [ AuthGuard ]
Run Code Online (Sandbox Code Playgroud)

和 app.route.ts :

  {
path: 'step2',
component: ProductOverviewComponent,
canActivate: [AuthGuard]
},
Run Code Online (Sandbox Code Playgroud)

毕竟,无论您在应用程序中使用导航,您只需将 Helper.isNextStep 设置为 true 即可。(例如,单击按钮会调用函数,因此在导航之前只需将静态字段设置为 true )

someButtonClickFunction() {
    Helper.isNextStep = true;
    this.zone.run(() => {
        this.router.navigate(['/step1']);
    });
}
Run Code Online (Sandbox Code Playgroud)

当加载下一个页面时,它会自动设置回 false,不允许 url 更改。