【问题标题】:How to read $stateParms value in Angular2?如何在 Angular2 中读取 $stateParms 值?
【发布时间】:2017-05-13 16:02:31
【问题描述】:

使用 Ui-Router 在 Angular1 中 stateparam 值是使用 $state.params

如何在 Angular2 中做同样的事情

我试过这样 this._uiRouter.globals.params.id

它正在工作,但它不是一个合适的解决方案,即使我正在使用 webstrome 编辑器, 编辑器还显示错误,例如 TS2339 Property id does not exits on typeStateParams,

请帮我做正确的方法

【问题讨论】:

  • 你检查过paramsthis._uiRouter.stateService.params 吗?
  • 是的,当我控制它时,我得到一个对象 StateParams {id:'1'}
  • 如果你需要的参数进来,你可以使用this._uiRouter.stateService.params来获取你的参数值
  • 如果我打印 this._uiRouter.globals.params.StatePams.id 它给出 undefined
  • 是的,我明白了,还有其他合适的方法

标签: angular angular-ui-router angular2-routing


【解决方案1】:

您可以在配置 URL 状态时从 Transition 可导出对象中获取状态参数:

import {Transition} from "ui-router-ng2";
...
export const personState = {
  name: 'person',
  url: '/people/:personId',
  component: Person,
  resolve: [
    { 
      token: 'stateParams', 
      deps: [Transition],
      resolveFn: (trans) => trans.params()
    }
  ]
};

然后在你的组件代码中:

import {Component, Input} from '@angular/core';
import {UIROUTER_DIRECTIVES, Transition} from 'ui-router-ng2';

@Component({  
  directives: [UIROUTER_DIRECTIVES],
  template: `
    <h2>stateParams</h2>
    <pre>{{ stateParams | json }}</pre>
`})

export class Person implements OnInit { 
  @Input() stateParams;

  ngOnInit() {
    // here you will have all passed state params
    console.log(this.stateParams);
  }

  constructor() {
  }
}

修改自https://ui-router.github.io/tutorial/ng2/hellosolarsystem#live-demo:https://plnkr.co/edit/IVGx0p9lQr1yKqgwZT4X的plunker

注意2个文件:

  1. state.ts
  2. components/person.ts

【讨论】:

  • @component 中的 UIRouter_DIRECTIVE 声明不可访问。
  • 如果你的意思是 UIROUTER_DIRECTIVES,那么它们是从 ui-router-ng2 模块导入的: import {UIROUTER_DIRECTIVES, Transition} from 'ui-router-ng2(我用 2 个导入更新了我的答案)';请检查工作插件:plnkr.co/edit/IVGx0p9lQr1yKqgwZT4X?p=preview,按“人物”链接,然后单击任何人 - 状态参数已 consol.logged 并打印在屏幕上。
【解决方案2】:

现在它变得更简单了。在你的构造函数中注入这个:

import {StateService} from '@uirouter/core';

private stateService: StateService

然后您可以通过此变量访问参数:

this.stateService.params

【讨论】:

  • 我认为这是一个更清洁的解决方案!谢谢:)
猜你喜欢
  • 2016-11-03
  • 2017-09-18
  • 2017-06-10
  • 1970-01-01
  • 2016-07-25
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
相关资源
最近更新 更多