首页 > 解决方案 > 如何使用不同的值而不是 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 上找到任何实现示例。

标签: angular

解决方案


我以前遇到过类似的事情。你为什么不改变你的路线,所以它使用名称而不是 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 名称。


推荐阅读