【发布时间】:2016-10-01 07:51:22
【问题描述】:
使用 ui-router 并尝试将 URL 查询参数传递给模块的 .config 中的控制器,使用已注入到 .state 定义的 resolve 参数中的 .service。
首选方法 - (不可靠)
.state('list', {
url: '/list?country&state&city',
templateUrl: "list.html",
controller : 'myController',
resolve: {
currentUrlTypeParam : ['myServices', function(myServices){ // object variable that can be injected into specified controller
return myServices.getUrlTypeParams();
}]
}
})
虽然文档说只有 Constant 和 Provider 配方可以注入到模块的 .config 函数中,但我遵循 .state 定义的 this method of injecting a .service into the resolve argument。
我使用服务的原因是我有许多具有相同 URL 查询参数的状态 - 所以作为服务提供者编写一次函数而不是重复它是有意义的。
我使用的是resolve,而不是直接将$stateParams 注入控制器,这样我就可以在配置期间完成服务器调用。
Here's a plunker 这个(显示 3 种可能的具有相同 URL 参数的状态) - 但是它不能可靠地工作 - 正确的 URL 参数似乎在第二次点击时到达相同状态的不同 URL。
更令人沮丧的是,虽然$stateParams 似乎在.service 函数中正确到达(在第一次点击时) - 但是在尝试访问它们时值出现为undefined - 检查plunker @987654338 @看到这个奇怪的现象!
例如console.log将在.service函数中输出$stateParams为:{country: "US", state: undefined, city: undefined}
但是,当我在函数中调用$stateParams.country 时,我得到undefined ??
替代梅西耶方法 - (工作正常)
替代方法是在 每个状态定义 的 resolve 参数中重复相同的大 .service 代码 - 这可以可靠地工作,但会使代码膨胀(...这是一个简化的示例我正在处理的状态/参数)。
.state('list', {
url: '/list?country&state&city',
templateUrl: "list.html",
controller : 'myController',
resolve: {
currentUrlTypeParam : ['$stateParams', function($stateParams){
var urlTypeParameter = {} // define an object that we'll return as the value for $scope.loadMethodParameters
if($stateParams.country && typeof $stateParams.country !== undefined){
urlTypeParameter.type = 'country';
urlTypeParameter.parameter = $stateParams.country;
} else if($stateParams.state && typeof $stateParams.state !== undefined){
urlTypeParameter.type = 'state';
urlTypeParameter.parameter = $stateParams.state;
} else if($stateParams.city && typeof $stateParams.city !== undefined){
urlTypeParameter.type = 'city';
urlTypeParameter.parameter = $stateParams.city;
} else {
urlTypeParameter.type = 'default';
}
return urlTypeParameter;
}]
}
})
请参阅this plunker 了解实现相同目标的一种相当……不优雅的方式。
【问题讨论】:
标签: javascript angularjs angular-ui-router