【问题标题】:Angular Sending an URL parm to a webserviceAngular 将 URL 参数发送到 Web 服务
【发布时间】:2019-07-04 02:33:10
【问题描述】:

为 TOH 前端创建了一个后端。 GetHeroes() 工作正常,所以基本的管道就位。

将 id 传递给 GetHero(id: number) 时遇到问题

Postman 获取以下 url 并返回

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]

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

【问题讨论】:

  • console.log('***' + this.route.snapshot.params.id); >>>>23 ,但我认为我正在阅读该快照并不是您真正想要使用的。访问英雄 21 和 23 将被缓存...
  • 您的网址是如何构建的?您是否使用查询字符串参数?你设置了什么样的路由机制?你用routerLink 构建你的URL?需要更多信息...
  • 顺便说一句,如果你认为它们会改变,你可以设置你的 url 参数来订阅 observable...
  • 所以要使用你的id,可以使用快照弹出它,或者像我在上一条评论中所说的那样订阅一个 observable。然后将其传递到您的服务中,并使用返回的数据执行您需要的任何操作。
  • fwiw - 我询问您的 url 是如何构建的原因是因为您在路由器中为参数提供的任何名称对于在组件上检索该参数的值都很重要...

标签: javascript angular typescript rxjs


【解决方案1】:

来自我对 OP 的评论 - 这是快照路线的示例。如果id 是动态的,您应该使用observable&lt;&gt;

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

【讨论】:

    【解决方案2】:

    在这里找到答案...

    https://scotch.io/tutorials/handling-route-parameters-in-angular-v2

    ngOnInit(): void {
        var hId: Number;
        this.route.paramMap.subscribe(params => {
          console.log( + params.get('id'));
          hId = params.get('id');
        });
    console.log(  hId);
    
            this.route.params
            .switchMap((params: Params) => this.heroService.getHero(+params.get('id')))
        }
    

    我不确定 TOH 使用的是哪个版本的 Angular。我猜 [ ] 在某些时候是一种有效的访问语法。

    【讨论】:

      猜你喜欢
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      相关资源
      最近更新 更多