2

I am trying to get value but it not working. below is my url I want to get 1 from url as number

https://localhost:44300/Portal#/user-edit/1

constructor(private router: Router,
    private userService: UserService) {

    this.router
        .routerState
        .queryParams
        .subscribe(params => {
            this.id = params['id'];
        });

2 Answers 2

5

You should inject ActivatedRoute to get route params as shown below,

constructor(private router: Router,
    private userService: UserService,
    private route: ActivatedRoute,) {  //<----- here

    this.route.params.subscribe(params => {
            this.id = +params['id'];   //<----- + sign converts string value to number
});

read more here : https://angular.io/docs/ts/latest/guide/router.html#!#route-parameters

Sign up to request clarification or add additional context in comments.

2 Comments

How about using route.snapshot.params['id'] ?
@kds23 if the id doesnt change (i.e. clicking on next button that displays another product without reinitializing the component) then you can use route.snapshot.params. But it's generally safer to use an observable.
1

Awesome reply! Just an add-on:

The property names have been updated. Use paramMap instead of params and queryParamMap instead of queryParams

See https://angular.io/guide/router#activated-route

An example:

constructor(private activatedRoute: ActivatedRoute) { }
    ngOnInit() {
    this.activatedRoute.paramMap.subscribe((params: ParamMap) => {
        console.log(params.get("id"));
    })
}

See this link for the available methods: https://angular.io/api/router/ParamMap

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.