javascript 使用 UI 路由器访问从解析函数调用的服务中新状态的 $stateParams
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18565221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access $stateParams of new state in service called from resolve function with UI Router
提问by nrw
Is there a way to access $stateParams
for the state you're transitioning to from a service called in a resolve function? With ngRoute
you'd use $route.current.params
. As this minimal plunk shows, the service only sees the state you're leaving:
有没有办法访问$stateParams
您正在从解析函数中调用的服务转换到的状态?随着ngRoute
你使用$route.current.params
。正如这个最小的 plunk 显示的那样,该服务只会看到您要离开的状态:
http://plnkr.co/edit/QpwgAj?p=preview
http://plnkr.co/edit/QpwgAj?p=preview
I get the new $stateParams
when $stateParams
is injected directly into a resolve function, but the values are still behind by one route in the service.
我得到了新的$stateParams
when$stateParams
直接注入到解析函数中,但这些值仍然落后于服务中的一个路由。
What am I missing?
我错过了什么?
采纳答案by laurelnaiad
You can't injectthe the incoming parameters into the service itself, but you can pass them to a functionin the service (or you could also assign them to a property in the service).
您不能将传入参数注入服务本身,但可以将它们传递给服务中的函数(或者您也可以将它们分配给服务中的属性)。
this plunkershows how to pass them to a function, which in turns stores them to a property in the service. Using a "dummy" property shouldn't hurt, but it is a bit ugly. :)
这个 plunker展示了如何将它们传递给一个函数,该函数又将它们存储到服务中的一个属性中。使用“虚拟”属性不应该受到伤害,但它有点难看。:)
It might make more sense to pass the parameters to the controller as a resolve property and then hand them out to a service from the controller constructor... that's what I'd do.
将参数作为解析属性传递给控制器,然后将它们从控制器构造函数传递给服务可能更有意义……这就是我要做的。
回答by Wilt
In your resolve function in stateprovider
在 stateprovider 的解析函数中
resolve: {
something: function(MyService, $stateParams){
return MyService.doSomethingWithParam($stateParams.someParameter);
}
}
In your service
为您服务
myService = angular.module('myService', [])
.factory('MyService', function() {
var myServiceInstance;
myServiceInstance.doSomethingWithParam= function(param){
//...store or do something with your state param here and return result
};
return myServiceInstance;
});