I can’t get the "id" parameter of the URL in Angular 12 using Activatedroute?

Asked

Viewed 45 times

-1

The URL 'user/1' for example, it doesn’t work. But I use '/user? id=1' works and I can list but it’s not in the format I want.

In my builder I declared an attribute ActivatedRoute, which I use in my method ngOnInit().

My declaration of routes:

const routes: Routes = [
  { path: ':id', component: UserComponent}
];

Man ngOnInit within the UserComponent:

ngOnInit(): void {
    this.route.queryParams.subscribe((params: any) => {
      this.userId = params['id'];
      console.log(this.userId);
    });
}

What am I doing wrong?

3 answers

1

When you use "subscribe", this function will usually only be triggered when there is some route change.

To capture the parameter as soon as the component starts, use the snapshot.

ngOnInit(): void {
    this.userId = this.route.snapshot.params["id"]
}

-3

You can get the value using the route snapshot.

Let id = this.route.snapshot.params.id;

-3

It’s because queryParams refers to query strings, so you can pick up when it’s ?id=1 to pick up the way you want, you must use this.route.params

Browser other questions tagged

You are not signed in. Login or sign up in order to post.