Angular UI路由器无法解析注入的参数

时间:2014-10-29 05:52:59

标签: angularjs angular-ui angular-ui-router

请考虑我的angularUI路由设置中的以下片段。我正在导航到路线/类别/管理/ 4 /详细信息(例如)。我希望'类别'要在相关控制器加载之前解决,实际上我可以在resolve函数中放置一个断点,该断点返回类别服务中的类别,并看到该类别已被返回。现在在控制器本身内放置另一个断点,我可以看到'类别'总是未定义的。它不是由UI路由器注入的。

有人能看到问题吗?它可能不是我提供的代码中的某个地方,但由于我在运行代码时没有错误,因此无法确定问题的根源所在。典型的js无声失败!

        .state('category.manage', {
            url: '/manage',
            templateUrl: '/main/category/tree',
            controller: 'CategoryCtrl'
        })
        .state('category.manage.view', {
            abstract: true,
            url: '/{categoryId:[0-9]*}',
            resolve: {
                category: ['CategoryService', '$stateParams', function (CategoryService, $stateParams) {
                    return CategoryService.getCategory($stateParams.categoryId).then(returnData); //this line runs before the controller is instantiated
                }]
            },
            views: {
                'category-content': {
                    templateUrl: '/main/category/ribbon',
                    controller: ['$scope', 'category', function ($scope, category) {
                        $scope.category = category; //category is always undefined, i.e., UI router is not injecting it
                    }]
                }
            },
        })
            .state('category.manage.view.details', {
                url: '/details',
                data: { mode: 'view' },
                templateUrl: '/main/category/details',
                controller: 'CategoryDetailsCtrl as details'
            })

1 个答案:

答案 0 :(得分:13)

这个概念正在发挥作用。我创建了working plunker here。这里的变化是

而不是

resolve: {
    category: ['CategoryService', '$stateParams', function (CategoryService, $stateParams) {
        //this line runs before the controller is instantiated
        return CategoryService.getCategory($stateParams.categoryId).then(returnData); 
    }]
},

我刚刚返回了getCategory的结果......

resolve: {
    category: ['CategoryService', '$stateParams', function (CategoryService, $stateParams) {
      return CategoryService.getCategory($stateParams.categoryId); // not then
    }]
},

天真的服务实施:

.factory('CategoryService', function() {return {
  getCategory : function(id){
    return { category : 'SuperClass', categoryId: id };
  }
}});

即使这是一个承诺......决心会等到它被处理......

.factory('CategoryService', function($timeout) {return {
  getCategory : function(id){
    return $timeout(function() {
        return { category : 'SuperClass', categoryId: id };
    }, 500);
  }
}});
相关问题