问题
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:
- state.ts
- 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