使用 ui-router,我像这样在状态函数中添加所有解析逻辑;
//my-ctrl.js
var MyCtrl = function($scope, customers) {
$scope.customers = customers;
}
//routing.js
$stateProvider.state('customers.show', {
url: '/customers/:id',
template: template,
controller: 'MyCtrl',
resolve: { // <-- I feel this must define as like controller
customers: function(Customer, $stateParams) {
return Customer.get($stateParams.id);
}
}
});
但是 IMO,resolve
对象必须属于 Controller ,如果在 Controller 文件中定义它,则易于阅读和维护。
//my-ctrl.js
var MyCtrl = function($scope, customers) {
$scope.customers = customers;
}
MyCtrl.resolve = {
customers: function(Customer, $stateParams) {
return Customer.get($stateParams.id);
};
};
//routing.js
$stateProvider.state('customers.show', {
url: '/customers/:id',
template: template,
controller: 'MyCtrl',
resolve: 'MyCtrl.resolve' //<--- Error: 'invocables' must be an object.
});
但是,当我将它定义为 MyCtrl.resolve
时,由于 IIFE,我得到以下错误。
Failed to instantiate module due to: ReferenceError: MyCtrl is not defined
当我将那个定义为字符串 'MyCtrl.resolve'
时,我得到了这个
Error: 'invocables' must be an object.
我看到 Controller 被定义为字符串,所以我认为也可以通过使用装饰器或其他东西将值作为字符串提供。
有没有人做过这种方法?这样我就可以保持我的 routings.js 干净并放置相关信息。在相关文件中?
最佳答案
这听起来像是建立决心的好方法,但我认为您做不到。
除了“resolve”需要一个对象这一事实之外,它是在一个阶段定义的,在这个阶段中您只能使用提供者。此时, Controller 甚至还不存在。
不过,更糟糕的是,“解析”意味着定义 Controller 本身的输入。要在 Controller 中定义解析,然后期望在创建 Controller 之前对其求值是循环依赖。
过去,我在$stateProvider
定义之外定义了解析函数,至少允许它们被重用。我从来没有尝试过比这更酷的东西。
var customerResolve = ['Customer', '$stateParams',
function(Customer, $stateParams) {
return Customer.get($stateParams.id);
}
];
// ....
$stateProvider.state('customers.show', {
url: '/customers/:id',
template: template,
controller: 'MyCtrl',
resolve: {
customers: customerResolve
}
});
关于javascript - Angular ui-router 将值解析为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30807930/