更改AngularJS的位置,并使用存储的路由。
更改AngularJS的位置,并使用存储的路由。
我试图将$routeChangeStart的“下一个路由”参数存储在一个服务中,并从不同的位置调用$location.path()来使用“下一个路由”。为了澄清一些代码:
$scope.$on('$routeChangeStart', function (event, next, current) { service.nextRoute = next; $rootScope.$broadcast('event:someEvent'); });
...现在我捕获了事件,并尝试做一些类似的事情(假设使用的服务都已正确注入和可用):
$rootScope.$on('event:someEvent', function() { //做一些事情 $location.path(service.nextRoute); });
我得到一个TypeError: Object #
的错误,来自于对$locaton.path(service.nextRoute);
的调用。这里还有一个stackoverflow上的类似问题的帖子,但是提出的解决方案似乎不起作用?那我做错了什么?
谢谢
问题的原因是使用了错误的方法来改变AngularJS的位置。使用了path()
方法,该方法接受一个字符串,其中next
是一个route {}
对象。实际上,应该使用$locationChangeStart
来获取路径。
解决方法是使用$locationChangeStart
事件来监听位置的变化。可以在监听函数中获取新的路径和旧的路径。
以下是解决方法的代码示例:
scope.$on('$locationChangeStart', function(event, newVal, oldVal) { // 在这里处理位置的变化 });
需要注意的是,根据这个答案,$locationChangeStart
是一个未记录的特性。