`ui-router` $stateParams 与 $state.params [英] `ui-router` $stateParams vs. $state.params

查看:24
本文介绍了`ui-router` $stateParams 与 $state.params的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ui-router,可以将 $state$stateParams 注入控制器以访问 URL 中的参数.但是,通过$stateParams 访问参数只公开属于访问它的控制器管理的状态的参数,及其父状态,而$state.params 具有所有参数,包括处于任何子州的那些.

With ui-router, it's possible to inject either $state or $stateParams into a controller to get access to parameters in the URL. However, accessing parameters through $stateParams only exposes parameters belonging to the state managed by the controller that accesses it, and its parent states, while $state.params has all parameters, including those in any child states.

给定以下代码,如果我们直接加载 URL http://path/1/paramA/paramB,则控制器加载时的情况如下:

Given the following code, if we directly load the URL http://path/1/paramA/paramB, this is how it goes when the controllers load:

$stateProvider.state('a', {
     url: 'path/:id/:anotherParam/',
     controller: 'ACtrl',
  });

$stateProvider.state('a.b', {
     url: '/:yetAnotherParam',
     controller: 'ABCtrl',
  });

module.controller('ACtrl', function($stateParams, $state) {
   $state.params; // has id, anotherParam, and yetAnotherParam
   $stateParams;  // has id and anotherParam
}

module.controller('ABCtrl', function($stateParams, $state) {
   $state.params; // has id, anotherParam, and yetAnotherParam
   $stateParams;  // has id, anotherParam, and yetAnotherParam
}

问题是,为什么不同?是否有关于何时以及为什么应该使用或避免使用其中任何一个的最佳实践指南?

The question is, why the difference? And are there best practices guidelines around when and why you should use, or avoid using either of them?

推荐答案

文档在这里重申了您的发现:https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service

The documentation reiterates your findings here: https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service

如果我没记错的话,$stateParams 的引入比原来的 $state.params 晚,而且似乎是一个简单的辅助注入器,可以避免连续编写 $state.params.

If my memory serves, $stateParams was introduced later than the original $state.params, and seems to be a simple helper injector to avoid continuously writing $state.params.

我怀疑是否有任何最佳实践指南,但上下文对我来说胜出.如果您只想访问接收到 url 的参数,请使用 $stateParams.如果您想了解有关状态本身的更复杂的信息,请使用 $state.

I doubt there are any best practice guidelines, but context wins out for me. If you simply want access to the params received into the url, then use $stateParams. If you want to know something more complex about the state itself, use $state.

这篇关于`ui-router` $stateParams 与 $state.params的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆