How to read $stateParms value in Angular2?

六眼飞鱼酱① 提交于 2019-12-24 07:59:19

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/41377832/how-to-read-stateparms-value-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!