Search code examples
angulartypescriptangular2-routing

Angular 7 direct url routing not working with id


If I click the navigation link I have code on button click it works fine

this.router.navigate(['/dashboard', this.selectedDateString]);

however, when I manually type in the url into the address bar like below

http://myapp/dashboard/01152020

I get a

forbidden!

message. Why does routing work from within the app but not from direct address bar typing?

Here is my routing module

const appRoutes: Routes = [
  { path: 'dashboard/:date', component: DashboardComponent },
  { path: 'dashboard', component: DashboardComponent },     
  { path: '',   redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes, { onSameUrlNavigation: 'reload' }
    )
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {}

Solution

  • I agree with @TheHeadRush.

    Sounds like you don't have your server configured to handle the frontend routes by returning the base document from those endpoints.

    If you don't want the server to handle that, you can tell Angular to use the HashLocationStrategy which will use hash fragments to navigate to pages.

    So instead of http://myapp/dashboard/01152020, your url will look like this in the browser http://myapp#/dashboard/01152020

    You will provide it in your root app module like so.

    @NgModule({
      imports: [
        BrowserModule,
        MyFeatureModule,
      ],
      providers: [
        {
          provide: LocationStrategy, useClass: HashLocationStrategy,
        },
      ]
    })
    export class AppModule {}