skyscript
skyscript

Reputation: 175

Multiple route names for the same page in Angular 2

Is it possible to have multiple route names for a page depending on how the user arrived at the page, but keeping the same RouteConfig path?

e.g.

@RouteConfig([
  {
    path: 'sweet/:id',
    name: 'SweetDetailLandingPage',
    component: SweetDetailComponent,
    data: { fromLink: false, fromDeepLink: true }
  },
{
    path: 'sweet/:id',
    name: 'SweetDetailFromLink',
    component: SweetDetailComponent,
    data: { fromLink: true, fromDeepLink: false }
  }
])

For example, if the user enters the URL into the browser, I want the app to load SweetDetailLandingPage. If the user arrives at the page internally via navigate(['SweetDetailFromLink']), I want to load SweetDetailFromLink.

The reason is because I want to determine whether the user arrived via a deep link or not and be able to call certain functions on load.

I tried this code but the app throws an error saying that there is a conflict.

ORIGINAL EXCEPTION: Configuration 'sweet/:id' conflicts with existing route 'sweet/:id'

I understand why there is a conflict. I'm just wondering if there is a way to implement what I explained above.

Upvotes: 3

Views: 688

Answers (2)

Diego Unanue
Diego Unanue

Reputation: 6836

What I would do in that case is: in the routerLinks add a query string parameter this._router.navigate(['SweetDetailLandingPage', {fromDeepLink: 'true'}]); and then in the load method where you want to deside to do something if you came from a deep link or not ask for that parameter:

if (this.getParameterByName('fromDeepLink') === 'true'){
     //do something
}else{
     //do something different
}

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657731

I would use a different approach. Read window.location.href either outside or (if it works inside Angular in the constructor of the root component) and if you get a deep link then redirect from there.

There is only one time during the application lifecycle whre a deep link can be loaded, this is when the application is loaded. Afterwards an URL change always results in a page reload. The only way to reach deep links afterwards is by the code of your Angular application (routerLink or router.navigateXxx() except you are using HashLocationStrategy instead of the default `PathLocationStrategy.

Upvotes: 2

Related Questions