我正在使用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'}
}
}
答案 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'}
}
}