Home > Enterprise >  404 Error Page displaying automatically when the application is load for the First Time in Angular 1
404 Error Page displaying automatically when the application is load for the First Time in Angular 1

Time:11-07

I have created a small application in Angular. I'm trying to make 404 Error Page in that application. If user put any wrong URL then this Error page will be Display automatically.

For that I have done - I have created a Separate Component name as "NotFoundComponent".

NotFoundComponent.html

<h1>Page Not Found !! </h1>
<a routerLink="/">Go back to Home Page</a>

app-routing.module.ts

const routes: Routes = [
  { path: 'about-us', component: AboutUsComponent },
  { path: 'how-it-works', component: HowItWorksComponent },
  { path: '**', component: NotFoundComponent },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  //providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],

})
export class AppRoutingModule { }

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    AboutUsComponent,
    HowItWorksComponent
  ],

  imports: [
    BrowserModule,
    AuthModule,
    UserModule,
    PublicModule,
    SharedModule,
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

If I'm putting any wrong URL than it is working as fine, It is showing 404 Error Page. i.e. NotFoundComponent.html.

But my problem is that when my application get load for the first time, it automatically displaying 404 Error Page or NotFoundComponent.html.

enter image description here

Rather than this, it is working fine, I have tried solution of HashLocationStrategy in app-routing.module.ts and but it won't work for me.

From my Point of view, I have set the correct order for Module in app.module.ts file and routing for app-routing.module.ts file.

Any help will be appreciated....Thank u!!

CodePudding user response:

The reason is that your root path is not configured in your routes config. This way the only route matching your root path is the "wildcard" route showing the NotFoundComponent.

In order to resolve the issue, you should define the root path and assign either a component to be rendered to it or assign a redirect path:

const routes: Routes = [
  // either define a component to be rendered: 
  // { path: '', pathMatch: 'full', component: MyHomeComponent },
  //
  // or redirect to a different route: 
  // { path: '', pathMatch: 'full', redirectTo: '/about-us' },
  { path: 'about-us', component: AboutUsComponent },
  { path: 'how-it-works', component: HowItWorksComponent },
  { path: '**', component: NotFoundComponent },
];
  • Related