1

我实际上有 $canActivate 的三个问题(另请查看下面的代码以更好地理解这些问题):

  1. 单击时,<a ng-link="['MachineDetails', { id: 'c6bd76947fc0' }]</a>我无法从 $canActivate 访问 id(url 和路由尚未更改,因此无法通过注入 $location 或注入 $rootRouter 获取它)
  2. 我想不出一种将数据从 $canActivate 传递到控制器的方法。
  3. 我无法从 $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 编写的组件定义。

4

1 回答 1

1
  1. 你可以注入$nextInstruction你的$canActivate钩子,然后你可以通过$nextInstruction.params.

    function canActivate($nextInstruction, $q, $rootRouter, machineDetailsService) {
      const machineId = $nextInstruction.params.id;
    }
    
  2. 我遇到了同样的问题,但找不到将数据从$canActivate挂钩传递到控制器的任何解决方案。

  3. 您可以导航到ListView通过$rootRouter.navigate(['/ListView'])。注意正斜杠。这需要指定,因为您ListView不是子路线。

于 2016-06-02T12:58:21.610 回答