Warm tip: This article is reproduced from stackoverflow.com, please click
angular javascript rxjs typescript

Angular Sending an URL parm to a webservice

发布于 2020-03-27 10:31:59

Created a backend for the TOH frontend. GetHeroes() is working fine, so the basic plumbing is in place.

Having troubles passing an id into GetHero(id: number)

Postman takes the following url and returns

http://192.168.1.125:4200/hero-detail/23  >>>>    { "id": 23, "name": "Celeritas1" }

Here is the ngOnInit from hero-detail.component.ts

 ngOnInit(): void {
    console.log('***' + this.route.params[0]);
        this.route.params
        .switchMap((params: Params) => this.heroService.getHero(+params['id']))
    }

Here is the GetHero() function from hero.service.ts The console.log is does not seem to be getting called. I am not getting an error in the web console or the ng command line window

private heroesUrl = 'http://localhost:4300/api/heroes';  // URL to web api

 getHero(id: number): Observable<Hero> {
    console.log("enter service.getHero");
   const url = `${this.heroesUrl}/${id}`;
    return this.http.get<Hero>(url).pipe(
      tap(_ => this.log(`fetched hero id=${id}`)),
      catchError(this.handleError<Hero>(`getHero id=${id}`))
    );
  }

Playing w/ the console.log in ngOnInit statement...

 console.log('***' + this.route.params[0]);     >>>    ***undefined

console.log('***' + this.route.params['id']);     >>>    ***undefined

console.log('***' + this.route.params );  >>>  ***[Object][Object]

My question is: It appears that the statement starting w/ switchMap is erroring out and not calling the service. What could I try to correct the error. And/or how can i reference the Param array using console.log to further diagnose the issue.

Questioner
greg
Viewed
104
Blair Holmes 2019-07-04 00:46

from my comment on the OP - here's an example of the snapshot route. If the id is dynamic though, you should use an observable<>

ngOnInit(): void {
    let id = +this.route.snapshot.paramMap.get('id'); // coerce your id to a number since that's what your service expects
        this.route.params
        .switchMap((params: Params) => this.heroService.getHero(id))
    }