简体   繁体   中英

Use route parameters in Angular 4 with ID is String

How to use route parameters with ID is String?

 {path: 'param/:id', component: MyComponent} 

 let id = this.route.snapshot.params['id']; 
Any idea

Blockquote

Using the route snapshot to get the id query parameter as you've shown should give you a string. If you want to implicitly convert that string to a number so you can use it in a route parameter for navigation, you can prefix the variable with a + :

// (+) converts string 'id' to a number
let id = +this.route.snapshot.params['id'];

Then:

this.router.navigate(['/example', id]);

Check out this example of getting the query param in the documentation https://angular.io/guide/router#snapshot-the-no-observable-alternative .

In the component you can use this code to transform from string into number:

 constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.paramMap
      .subscribe((params: ParamMap) => {
        let id = +params.get('id'); // This line converts id from string into num
      });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM