Converting route parameter types

I am currently browsing the Angular 2 tutorial and learning how to use a router with parameters to retrieve object data by id.

Below is the code used to link to the question I asked.

Here is the route definition in app.module.tsto point to the component based on id

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

A service method (from the Service class) for capturing data based on id

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

Both the constructor and the OnInit method (from hero-details.componentent, where the data will be displayed) used to pull 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 example of the data that we pull out. id is the type and string of the name type.

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

: . ngOnInit this.heroService.getHero(). +params['id'] ? , , app.module.ts detail/:id params['id'], , , .

+4
1

params - Angular2 , . : id () . .

(+ params ['id']), , javaScript, param () .

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

, , .

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

Source: https://habr.com/ru/post/1663435/


All Articles