angular - 如何使用不同的值而不是 id
问题描述
此时,从 .json 文件中获取项目后:
目录items.service.ts
/** GET item by id. Will 404 if id not found */
getCatalogItem(id: number): Observable<CatalogItem> {
const url = `${this.catalogitemsUrl}/${id}`;
return this.http.get<CatalogItem>(url);
}
目录项.component.ts
getCatalogItem(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.catalogItemsService.getCatalogItem(id)
.subscribe(catalogitem => this.catalogitem = catalogitem);
}
我的动态链接如下所示:“ sitename.com/catalog/id ”
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'catalog', component: CatalogComponent },
{ path: 'catalog/:id', component: CatalogItemComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
如果我们将浏览器直接指向 sitename.com/catalog/ page_title ,是否可以使用另一个接收到的值而不是 id ?我没有在 Internet 上找到任何实现示例。
解决方案
我以前遇到过类似的事情。你为什么不改变你的路线,所以它使用名称而不是 id:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'catalog', component: CatalogComponent },
{ path: 'catalog/:name', component: CatalogItemComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
然后您的目录项服务可以将名称作为参数来检索目录项:
getCatalogItem(name: string): Observable<CatalogItem> {
const url = `${this.catalogitemsUrl}/${name}`;
return this.http.get<CatalogItem>(url);
}
并将您的 catalog-component-item 更改为使用名称:
getCatalogItem(): void {
const name = this.route.snapshot.paramMap.get('name');
this.catalogItemsService.getCatalogItem(name)
.subscribe(catalogitem => this.catalogitem = catalogitem);
}
这确实意味着您需要更改 api。但是使用此实现,您也不能有重复的 CatalogItem 名称。
推荐阅读
- python - i(ContentsOwner, MCN) 在哪里可以找到 Youtube 报告 API 中的 Finalized Red(Premium)&Superchat 收入数据?
- excel - 如何使用 vba 将同一目录中的文件复制到另一个目录?
- spring - Spring Conditional SpEL 无法解析
- tensorflow - InvalidArgumentError:无法序列化 tensorflow.GraphDef 类型的协议缓冲区
- python - 无法安装/更新任何包/conda/navigator?
- flowtype - 如何在 React HOC 中描述流移除道具
- javascript - js 事件,如果用户点击浏览器的上下文菜单
- circuit-sdk - 电路 API 问题
- callback - RabbitMQ 是否为消费者保持开放连接?
- javascript - 当我将目的地设置为另存为 PDF 时,window.print() 不显示更多设置