How to read $stateParms value in Angular2?

2019-07-25 15:26发布

Using Ui-Router In Angular1 The stateparam value is coming using $state.params

How to do the same thing in ANgular2

I tried like this this._uiRouter.globals.params.id

it's working, But its not a proper solution, even I am using webstrome editor, the editor also showing error like TS2339 Property id does not exits on typeStateParams,

Please help me do proper way

2条回答
祖国的老花朵
2楼-- · 2019-07-25 16:01

you can get state parameters from the Transition exportable object while configuring URL state:

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()
    }
  ]
};

then in you component code:

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() {
  }
}

modified plunker from the https://ui-router.github.io/tutorial/ng2/hellosolarsystem#live-demo: https://plnkr.co/edit/IVGx0p9lQr1yKqgwZT4X

pay attention to 2 files:

  1. state.ts
  2. components/person.ts
查看更多
冷血范
3楼-- · 2019-07-25 16:11

These days it's simpeler. In your constructor inject this:

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

private stateService: StateService

You can then access the params via this variable:

this.stateService.params
查看更多
登录 后发表回答