MrNew
MrNew

Reputation: 1414

Angular2 get Url parameter and display it on template

I have an item listing app and with various stores, I managed to set a default store and fetch the items based on storeId and build a url param /store/3.

What I'm planning to do is to show the locationName of this storeId in my template say store 3 is London, so I want to show something like Collection Store - London I managed to do it with its Id but showing Collection Store - 3 doesn't really make sense.

This is my stores which is in my nav.component

this.sourceSites = [
  {
    'Id': 1,
    'StoreLocation': 'Eastleigh'
  },
  {
    'Id': 2,
    'StoreLocation': 'Portchester'
  },
  {
    'Id': 3,
    'StoreLocation': 'London'
  },
  {
    'Id': 4,
    'StoreLocation': 'Basingstoke'
  }
]

Nav template

<li *ngFor="let store of sourceSites" 
    [class.active-location]="storeId === store.Id  || (storeName === store.StoreLocation)">
  <a [routerLink]="['/order-screen/store/' + store.Id + '/' +store.StoreLocation]">
      {{ store.StoreLocation}}
  </a>
</li>

To show the storeId,I have this in my order-component

ngOnInit() {
  this.routeSub = this.route.params.subscribe(params => {
     this.storeId = +params['storeId'];
     if (!this.storeId) { 
        this.storeId = DEFAULT_ORIGIN_ID; 
     } 
  })
}

To use default Id 3 I put export const DEFAULT_ORIGIN_ID = 3. Though doing this is fine, but this only shows the StoreId instead I want to show StoreLocation

My attempt is to add another URL parameter /store/3/Location and create another export const DEFAULT_ORIGIN_LOCATION = 'London' in my sharedService. and put else if() condition in the ngOnInit

ngOnInit() {
   this.routeSub = this.route.params.subscribe(params => {
      this.storeId = +params['storeId'];
      this.storeName = +params['storeName'];
      if (!this.storeId) { 
         this.storeId = DEFAULT_ORIGIN_ID; 
      } else if (!this.storeName) {
         this.storeName = DEFAULT_ORIGIN_LOCATION;
      }  
    this.getOrdersFromOrigin(this.storeId);
 })
}

But when I do this, it shows me Collection Store - London however when I change my location to something else the location London persist.

How can I make the DEFAULT_ORIGIN_NAME to change when I change my location?

Edit With child route, its not changing the url path now.

{ path: 'order-screen/store/:storeId', component: OrderComponent, 
   children: [
      {
         path: ':storeName',
         component: OrderComponent,  
      }
   ] 
}

Upvotes: 0

Views: 123

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657068

When you have routes like

routes = [
  { path: '', pathMatch: 'full', redirectTo: '/order-screen/store/3/London'}, 
  { path: 'order-screen/store/:storeId', component: SomeComponent, 
       children: [...] }
];

then your code should work.

Upvotes: 1

Related Questions