我实际上有 $canActivate 的三个问题(另请查看下面的代码以更好地理解这些问题):
- 单击时,
<a ng-link="['MachineDetails', { id: 'c6bd76947fc0' }]</a>
我无法从 $canActivate 访问 id(url 和路由尚未更改,因此无法通过注入 $location 或注入 $rootRouter 获取它) - 我想不出一种将数据从 $canActivate 传递到控制器的方法。
我无法从 $canActivate 重新路由(通过使用 $rootRouter.navigate())。
import template from './machine-details.html'; export const machineDetailsComponent = { template: template, controller: machineDetailsController, $canActivate: canActivate, }; /*@ngInject*/ function machineDetailsController (machineDetailsService) { this.$routerOnActivate = function (nextRoute) { // do something; }; } /*@ngInject*/ function canActivate ($q, $rootRouter, machineDetailsService) { const deferred = $q.defer(); /** * ISSUE 1: * if I get here via ng-link, then $rootRouter.lastNavigationAttempt * shows the route I was on when clicking, however if I type the url manually * (or refresh) I get something I can use which is for example '/machineDetails/c6bd76947fc01' **/ const machineId = $rootRouter.lastNavigationAttempt.split('/')[2]; machineDetailsService.getMachineDetailsData(machineId) .then(successHandler, errorHandler); /** * ISSUE 2: * 'result' does not make its way into controller so I need to call * machineDetailsService.getMachineDetailsData again in controller... **/ function successHandler (result) { deferred.resolve(); // passing on result has no affect } function errorHandler (error) { deferred.resolve(error); /** * ISSUE 3: * $rootRouter.navigate doesn't work here (and controller is * never called) so how do I cause system to go back to list view ? **/ // $rootRouter.navigate(['ListView']); } return deferred.promise; }
上面的代码是我用 ES6 编写的组件定义。