温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Angular Sending an URL parm to a webservice
angular javascript rxjs typescript

javascript - 将URL参数发送到Web服务

发布于 2020-03-27 12:07:37

为TOH前端创建了一个后端。GetHeroes()正常运行,因此基本的管道就位。

将ID传递到GetHero(id:number)时遇到麻烦

Postman 输入以下网址并返回

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

这是hero-detail.component.ts中的ngOnInit

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

这是hero.service.ts的GetHero()函数, 似乎未调用console.log。我在Web控制台或ng命令行窗口中未收到错误

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}`))
    );
  }

正在ngOnInit语句中与console.log一起播放...

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

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

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

我的问题是:看来以w / switchMap开头的语句出错了,没有调用服务。我该如何尝试纠正错误。和/或如何使用console.log引用Param数组以进一步诊断问题。

查看更多

查看更多

提问者
greg
被浏览
147
Blair Holmes 2019-07-04 00:46

根据我对OP的评论-这是快照路由的示例。如果id是动态的,则应使用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))
    }