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>
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:
When you are using angular routing, you must define a default route like this:
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.