【发布时间】: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