Thinker
Thinker

Reputation: 5366

Angular2 hashed urls get current url

I have defined my routes like following:

const appRoutes: Routes = [
{
  path: 'auth',
  component: AuthenticationComponent,
},
{
  path: '',
  component: HomeComponent,
  canActivate:[AuthenticationGuard],
  children:[
  {
    path: 'list',
    component: TaskListComponent,
    canActivate:[AuthenticationGuard]
  },
  {
    path: 'create',
    component: CreateTaskComponent,
    canActivate:[AuthenticationGuard]
  },
  {
    path: 'profile',
    component: ProfileComponent,
    canActivate:[AuthenticationGuard]
  },
  {
    path: 'agreement',
    component: UserAgreementComponent,
    canActivate:[AuthenticationGuard]
  },
  ]

},

];

And I navigate on them like following:

<nav class="mdl-navigation">
    <a class="mdl-navigation__link" href="#/list">List</a>
    <a class="mdl-navigation__link" href="#/create">Create</a>
    <a class="mdl-navigation__link" href="#/profile">Profile <span *ngIf="profileNotPresent" mdl-badge="Start"></span> </a>
    <button class="mdl-button mdl-js-button" (click)="logout()">
        <i class="material-icons">exit_to_app</i>
    </button>
</nav>

I had to add hash because when I deployed the app it started throwing me 404 error for routes. With hashed urls it works.

However in my code I had a condition where I was showing a div on condition that was true if it was the base route:

if(this.router.url == '/'){
    this.showHomeContent=true;
}

that time without hash my urls were '/', '/profile' etc and it used to work corrrrectly. Now they are '#', '#/profile' etc and this condition no longer works resulting in that specific div always remains open.

How can I fix this?

Upvotes: 0

Views: 194

Answers (2)

Vic
Vic

Reputation: 424

It's kinda explained in the docs - PathLocationStrategy

Router supports two kinds of strategies PathLocationStrategy and HashLocationStrategy

If you use PathLocationStrategy you must provide APP_BASE_HREF or insert in your index.html head the <base href="/">

This should fix your issue.

Upvotes: 0

Yakov Fain
Yakov Fain

Reputation: 12376

You need start using Angular router for navigation. I mean [routerLink] instead of href. Without the # you may be getting 404 if you enter a URL the trying to get a to a not-known resource. By default, Angular uses PathLocationStrategy, which makes a server request in this situation.

If you'd be using Router navigation, you could fix this issue by configuring a redirect to the index.html, and then the router would navigate properly.

So start using the Router properly, and in your app module add this:

 providers:[{provide: LocationStrategy, useClass: HashLocationStrategy}]

The Router will be adding a #-sign to the URLs and won't be making server-side requests resulting in 404. But again, replace your hrefs with the routerLink directives first.

Upvotes: 1

Related Questions