Lolo Ogly
Lolo Ogly

Reputation: 25

How to use a different value instead of id

At this moment, after getting item from .json file:

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

catalog-item.component.ts

  getCatalogItem(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    this.catalogItemsService.getCatalogItem(id)
      .subscribe(catalogitem => this.catalogitem = catalogitem);
  }

my dynamic links looks like this: "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 }
];

Is it possible to use another received value instead of id which will be shown if we point our browser directly to sitename.com/catalog/page_title? I did not find any implementation examples over the Internet.

Upvotes: 0

Views: 86

Answers (1)

ViqMontana
ViqMontana

Reputation: 5688

I've come across something similar before. Why don't you change your routes so it uses name instead of 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 }
];

Then your catalog-item-service could take the name as a parameter to retrieve the CatalogItem:

getCatalogItem(name: string): Observable<CatalogItem> {
    const url = `${this.catalogitemsUrl}/${name}`;
    return this.http.get<CatalogItem>(url);
  }

And change you catalog-component-item to take the name instead:

getCatalogItem(): void {
    const name = this.route.snapshot.paramMap.get('name');
    this.catalogItemsService.getCatalogItem(name)
      .subscribe(catalogitem => this.catalogitem = catalogitem);
  }

This does mean you'll need to change you api. But with this implementation, you cannot have duplicate CatalogItem name's either.

Upvotes: 1

Related Questions