在角应用程序(移动)中防止向后导航

时间:2017-11-10 15:19:39

标签: javascript angular

我需要阻止用户在我正在构建的应用的某些部分进行向后导航。到目前为止,我正在使用这种方法:

ngOnInit() { 

 history.pushState(null, null, location.href);   
 window.onpopstate = function(event) {
   history.go(1);
 };
}

ngOnDestroy() {
 window.onpopstate = function(event) {
   history.go();
 };
}

除了iOS chrome和safari之外,这个功能很棒。我也试过了:

history.replaceState(null, document.title, location.pathname);

在ngOnInit中没有运气。有人可以告诉我这些移动设备上的浏览器如何使用历史记录和/或popstate不同于Windows / macOS版本的浏览器?

1 个答案:

答案 0 :(得分:2)

我不会尝试实施不同的浏览器特定解决方案,而是会考虑Angular的CanDeactivate guard

假设您有一个始终存储上一条路线的服务(让我们称之为NavigatorService):

@Injectable()
export class NavigatorService{
  private previousRoute:string = null;
  private currentRoute:string = null;
  /** Listen to and log new route paths */
  constructor(private router:Router){
    router.events.filter(e => e instanceof NavigationEnd).subscribe(
      e => {
        this.previousRoute = this.currentRoute;
        this.currentRoute = e['url'];
      }
    )
  }
  /** Checks whether the next route corresponds to the previous route  */
  isGoingBack(nextState:RouterStateSnapshot){                   
      return nextState.url === this.previousRoute;
  }
}

接下来创建一个CanDeactivateGuard,它将依赖此服务来确定是否允许用户离开当前视图:

@Injectable()
export class BackwardGuard implements CanDeactivate<any> {
  // Inject the service needed
  constructor(navigatorService:NavigatorService){}

  // Angular 4 provides these arguments to any CanDeactivate guard
  // see https://angular.io/api/router/CanDeactivate#interface-overview
  canDeactivate(component:any, currentRoute:ActivatedRouteSnapshot, 
             currentState:RouterStateSnapshot, nextState:RouterStateSnapshot){                   
      // Allow navigation only if the user is not going back
      return !this.navigatorService.isGoingBack(nextState);
  }
}

最后,在要保护其组件的路线上注册此防护措施:

appRoutes:Routes = [
  {
    path: 'some-path',
    component: ProtectedComponent,
    canDeactivate: [BackwardGuard]
  }
];

这个未经测试的代码可能存在错误,但我认为一旦你解决它们,它应该可行。请务必向您的组件模块提供NavigatorService(例如:AppModule)并向匹配的路由模块提供BackwardGuard(例如:AppRoutingModule