Route params type conversion

14.7k views Asked by At

I'm currently going through the Angular 2 tutorial and learning how to use the router with parameters to fetch object data by an id.

Below is the code used in reference to the question I will ask.

Here is the route definition withinapp.module.tsfor directing to a component based on an id

      {
        path:'detail/:id',
        component:HeroDetailComponent
      }

Service method (from Service class) for grabbing the data based on id

getHero(id: number): Promise<Hero> {
    return this.getHeroes()
    .then(heroes => heroes.find(hero => hero.id === id));
}

And the constructor and OnInit method (from hero-details.component where data will be displayed) used for pulling the information from the url

constructor(
private heroService: HeroService,
private route: ActivatedRoute,
private location: Location
){}

ngOnInit():void{
  this.route.params
    .switchMap((params:Params) => this.heroService.getHero(+params['id'])
      .subscribe(hero => this.hero = hero));
}

And finally an exmaple of the data we're pulling in. id is type number and name type string.

{ id: 11, name: 'Mr. Nice' }

QUESTION: Within the ngOnInit we convert the id from a string to a number within the parameters of the this.heroService.getHero() call. How exactly does the +params['id'] work in terms of conversion? My guess was that it's due to the way we laid out the route within the app.module.ts file and that detail/:id is equivalent to params['id'] but I want a clear explination so that I know what I'm doing with certainty in the future. Thank you

1

There are 1 answers

0
MickG On BEST ANSWER

The params object is a construct built and populated by the Angular2 router to hold the parameters you specify on the routes. The key value pairs match the :id (key) and the actual route value at runtime. Params can hold more than one parameter.

The plus (+params['id']) you are referring to is a standard javaScript operator that tells the interpreter to convert the param result from whatever type it is (string) into a number.

See this reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_(.2B)

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

+3     // 3
+"3"   // 3
+true  // 1