用angular 1.5的组件路由处理浏览器刷新事件

handle browser refresh event with angular 1.5 component routing

本文关键字:处理 浏览器 刷新 事件 路由 组件 angular      更新时间:2023-09-26

我已经实现了Angular 1.5 component routing。当用户通过单击或键盘F5刷新浏览器时,我正在寻找解决方案。它应该将用户重定向到第一页,并应该重置所有输入/选择的数据。

这是PLUNKER。这只有两页。

在我的例子中,如果用户刷新。用户应重定向到First页面,所有输入/选择的数据将重置为默认值。

注意:我知道Angular 1.5的组件路由被弃用了。遗憾的是,我是在应用投入生产后才知道这一点的。在我们迁移到Angular2之前,我必须为用户提供一些解决方案。

下面是处理组件路由的代码:
var module = angular.module('app', ['ngComponentRouter']);
module.config(function($locationProvider) {
  $locationProvider.html5Mode(true);
});
module.value('$routerRootComponent', 'myFirstApp');
module.component('myFirstApp', {
  templateUrl: "mainview.html",
  $routeConfig: [{
    path: '/',
    redirectTo: ['/First']
  }, {
    path: '/first',
    name: 'First',
    component: 'firstComponent'
  }, {
    path: '/second',
    name: 'Second',
    component: 'secondComponent'
  }]
})

我能够做到这一点,唯一的事情是需要以编程方式处理路由。这一行正在执行神奇的window.onbeforeunload = $rootRouter.navigate(['First']);

确保注入$rootRouter & $window服务。

module.component('firstComponent', {
templateUrl: "1.html",
controllerAs: "vm",
controller: function($rootScope, sharedService, $rootRouter, $window) {
  window.onbeforeunload = $rootRouter.navigate(['First']);
}