使用angular ui路由器将$ scope和promise结果注入到控制器构造函数中

时间:2017-08-03 10:08:21

标签: javascript angularjs typescript angular-ui-router

我正在使用angular ui router,我需要将$scope和一些预先获取的数据注入我的控制器构造函数。

当我只将promise添加到resolve对象时,我能够实现这一点,只要我将$scope服务添加到注入的列表中,angular ui路由器无法解析路由。

工作打字稿代码:

$stateProvider.state('parent.child', {
    url: '/child',
    template: 'I am the child state',
    controller: 'TestController',
    controllerAs: 'vm',
    resolve: {                
        viewModel:initializeControllerViewModel
    }
});

initializeControllerViewModel.$inject = [
    '$stateParams',
    '$q',
    '$timeout'
];

function initializeControllerViewModel(
    $stateParams: ng.ui.IStateParamsService,
    $q: ng.IQService,
    $timeout:ng.ITimeoutService)
{
    let deferred = $q.defer();

    $timeout(() =>
    {
        deferred.resolve({
            property1: 'foo'
        });
    }, 500);

    return deferred.promise;    
}

class TestController
{
    constructor(
        viewModel: any)
    {            
        //viewModel should be {property1: 'foo'}
    }
}

不工作代码:

$stateProvider.state('parent.child', {
    url: '/child',
    template: 'I am the child state',
    controller: 'TestController',
    controllerAs: 'vm',
    resolve: {
        '$scope': '$scope',
        viewModel:initializeControllerViewModel
    }
});

class TestController
{
    constructor(
        $scope: ng.IScope,
        viewModel: any)
    {
        //$scope should be injected
        //viewModel should be {property1: 'foo'}
    }
}

1 个答案:

答案 0 :(得分:0)

从ui路由器中删除范围并尝试在类中使用$ inject属性

class TestController
{
public static $inject = ['$scope', 'viewModel'];
constructor(
        $scope: ng.IScope,
        viewModel: any)
    {
        //$scope should be injected
        //viewModel should be {property1: 'foo'}
    }
}
相关问题