wangzixi-diablo / Spartacus-learning

record questions raised during my study
0 stars 1 forks source link

routerLink does not work as expected #3

Open wangzixi-diablo opened 4 years ago

wangzixi-diablo commented 4 years ago

I have created a custom module with the following routing settings:

const CUSTOM_ROUTES: Routes = [
  { path: 'custom', component: CustomPageComponent, canActivate: [CmsPageGuard] },
  { path: 'custom2', component: CustomPageComponent },
  {
    path: 'faq-alias', component: PageLayoutComponent, canActivate: [CmsPageGuard],
    data: {
      pageLabel: 'faq'
    }
  }
];

clipboard1,1

@NgModule({
  declarations: [CustomPageComponent],
  imports: [
    CommonModule,
    UrlModule,
    RouterModule.forChild(CUSTOM_ROUTES),
    ConfigModule.withConfig({
      routing: {
        routes: {
          product: {
            paths: [
              'jerrycamera/:manufacturer/:name/:productCode',
              'cameras/:name/:productCode'],
            paramsMapping: {
              name: 'nameForUrl'
            }
          }
        }
      }
    } as RoutingConfig),

the /custom url points to my custom component with html template below:

<p>custom-page works!</p>

<a href="/cameras/photosmart-e317-digital-camera/300938">Awesome Product</a>

<p></p>
<a [routerLink]="{ cxRoute: 'product', params: {code: '300938'}} | cxUrl">Awesome Product 2</a>

clipboard2,2

when I click hyperlink "Awesome Product 2", I expect to navigate to the product detail page for product 300938:

clipboard3,3

Unfortunately it does not work. When I click the hyperlink, it will open http://localhost:4200/electronics-spa/en/USD instead.

I observed in Chrome development tool, that every time I open url http://localhost:4200/electronics-spa/en/USD/custom, there is warning message reported in Chrome console:

clipboard4,4

No configured path matches all its params to given object. Route config:

clipboard5,5

This just points to my route configuration hard coded in .

clipboard6,6

I am exactly following the same source code as found in training video:

clipboard7,7

wangzixi-diablo commented 4 years ago

My Analysis

I set a breakpoint in function generateUrlPart in file Spartacus-core.js:

clipboard1,1

For every path stored in routeConfig.paths, this function evaluates if route parameter passed by developers in can match ALL.

clipboard2,2

Since I only specify "code" in my custom component template html,

clipboard3,3

the evaulation will fail of course, as no counterpart exists for another parameter "name":

clipboard4,4

solution

After I add the other necessary route parameter nameForUrl: 'Jerry' in my html:

clipboard5,5

this time function generateUrlPart can return the expected result:

clipboard6,6

This time route works since the static url is generated successfully and contained in the rendered html.

clipboard7,7