Search code examples
angularangular2-routing

Angular Routing not Working (Error: The Site Cannot Be Found)


After creating a new app in NX workspace, I am using two components at the moment. Homepage and Product List Page. When I try to create router links, the site displays the error that "Site Cannot Be Reached"

Here is my app module ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { RouterModule, Routes } from '@angular/router';
//import { appRoutes } from './app.routes';
import { HomePageComponent } from './pages/home-page/home-page.component';
import { ProductListComponent } from './pages/product-list/product-list.component';

const routes: Routes = [
  { path: '', component: HomePageComponent}, 
  { path:'products', component: ProductListComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    HomePageComponent,
    ProductListComponent,
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
    //RouterModule.forRoot(appRoutes, { initialNavigation: 'enabledBlocking' }),
  ],
  providers: [],
  bootstrap: [AppComponent],
  
})


export class AppModule {}

And naturally I declared the correct path on my app component (root) page:

<router-outlet></router-outlet>

Solution

  • The routes object doesn't have a default route so when you open your app in browser the URL is "http://localhost:4200/" and this route is not in the list of your routes.

    The solution for this problem is to change routes object to this one:

        const routes: Routes = [
          { path: 'home', component: HomePageComponent},
          { path: 'products', component: ProductListComponent},
          { path: '', redirectTo: '/home', pathMatch: 'full'},
        ]
    

    I made these changes in routes object:

    1. Changed the route to your home page from '' to 'home'.
    2. Added a default route (fallback route) at the end of the routes object.

    When you are using angular routing, you must define a default route like this:

    • The path must be "" (an empty string).
    • Use redirectTo property with value of your main page (in your case it is '/home')
    • Use pathMatch property with value of 'full' that any route which is not defined in routes object, be redirected to your home page.

    Tip: For a good practice, i recommend you to create a 404 page component and when a path does not exist redirect users to that component instead of your home page. Also put a navigation menu there for your available routes.