Routing through links in Angular2 - angular2-routing

I am new in Angular 2 and I am still in learning phase, but I stuck in a problem and not getting the solution to it. Please help.
I have made a view of a login, then a link to it after clicking the link it will redirect to home then clicking a link there it will redirect to some other view.
Below is my code structure:
app.routing.ts:
import { Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { UsersComponent } from './users/usercomponent';
export const routes: Routes = [
{ path: 'Home', component: HomeComponent },
{ path: 'Login', component: LoginComponent },
{ path: 'User', component: UsersComponent },
];
app.module.ts:
import { FormsModule } from '#angular/forms';
import { routes } from './app.routing';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { UsersComponent } from './users/usercomponent';
#NgModule({
imports: [BrowserModule, FormsModule, RouterModule.forRoot(routes)],
declarations: [AppComponent, LoginComponent, HomeComponent, UsersComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
import { Component } from '#angular/core';
import { OnInit } from '#angular/core';
#Component({
selector: 'app-initializer',
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'Some NAme'
}
app.component.html:
<a routerLink="Login">Login</a>
<br />
<div>
<router-outlet></router-outlet>
</div>
login.component.ts:
import { Component } from '#angular/core';
#Component({
selector: 'login',
template: `
<h1><a routerLink="Home">Home</a>
<a routerLink="User">Users</a></h1>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class LoginComponent {
constructor() {
}
}
The first page is working but after clicking home it is giving an error:
Cannot match any routes. URL Segment: 'Login/Home
I know that the link will be like / login, /home etc not like /login/home but how to implement it as I am not getting the solution for it and I am completely new to it.

Instead of giving only <h1><a routerLink="Home">Home</a>
you need to add / before the link like <h1><a routerLink="/Home">Home</a>.

Related

What am I missing so I can use the router on Nativescript?

I am attempting to build my first ever app using nativescript. I am going through the docs but not sure what I'm missing so I can't fix it.
I have the following structure:
- app
-- app-routing.module.ts
-- app.component.html
-- app.component.ts
-- app.css
-- app.module.ts
- home
-- home.component.css
-- home.component.html
-- home.component.ts
- restaurant
-- restaurant.component.css
-- restaurant.component.html
-- restaurant.component.ts
The thing is, I am trying to make it so that when someone taps on an element in the home.component.html:
<Image class="h3 m-5" col="0" row="0" src="~/images/beet-logo.jpg" (tap)="visitRestaurant()" height="87" width="80"></Image>
They are redirected to the restaurant.component.html page.
I defined the tap event as shown up there and then I have on my home.component.ts the following:
import { Router } from "#angular/router";
import { Component, OnInit } from "#angular/core";
#Component({
selector: "Home",
moduleId: module.id,
templateUrl: "./home.component.html",
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private router: Router) {
}
visitRestaurant() {
this.router.navigate(["/restaurant"]);
}
ngOnInit(): void {
}
}
When I click it, it fails though with the error:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
URL Segment: 'restaurant'
I thought about adding the route here and also into app-routing.module.ts but whenever I try I get cannot find name: RestaurantComponent. So I assume I need to export the component somewhere but not sure where or how.
Can you guys help me?
This is my app-routing-module.ts in case it's useful:
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: "./home/home.module#HomeModule" }
];
#NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }
Here's my restaurant.component.ts code:
import { Router } from "#angular/router";
import { Component, OnInit } from "#angular/core";
#Component({
selector: "Restaurant",
moduleId: module.id,
templateUrl: "./restaurant.component.html",
styleUrls: ['./restaurant.component.css']
})
export class RestaurantComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit(): void {
}
}
You need to add a route for /restaurant. For example, you might do:
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: "./home/home.module#HomeModule" },
{ path: "restaurant", component: RestaurantComponent }
];
Additionally, you'll want to make sure your export/import statements appear appropriately.
Within restaurant.component.ts:
#Component({ ... })
export class RestaurantComponent { ... }
Within app-routing.module.ts:
import { RestaurantComponent } from ' ... ';

Populating a child router-outlet Angular2 not working

The solution below was the first attempt as below.
Created app.module.ts and app.route.ts.
Created default for app.component.ts. The app.component router is working as expected so far for the first level routing.
Created a new module called Dashboard, with dashboard.module.ts and dashboard.routes.ts.
I imported the dashboard into the app.module.ts.
Created Sitebar,Header, and HeaderNav in the Dashboard.component.ts with child . But, no idea why the child navigation always shows in the first level router-outlet, instead of the child router-outlet.
Dashboard.component.ts code below.
<div class="wrapper">
<app-mydash-sidebar
[headerText]="'No Rush'"
[headerLink]="'http://www.bit-numbers.com'"
[headerLogoImg]="'/assets/img/angular2-logo-white.png'"
[backgroundColor]="'red'"
[backgroundImg]="'/assets/img/sidebar-5.jpg'"
[navItems]="navItems">
</app-mydash-sidebar>
<div class="main-panel">
<app-mydash-navbar [navItems]="navItems"></app-mydash-navbar>
<router-outlet ></router-outlet>
</div>
</div>
app.component.ts below.
<router-outlet></router-outlet>
Any idea?
app.routes.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { MembersComponent } from './members/members.component';
import { AuthGuard } from './auth.service';
import { SignupComponent } from './signup/signup.component';
import { EmailComponent } from './email/email.component';
import { HomeComponent } from './home/home.component';
import { BookingsComponent } from './bookings/bookings.component';
export const router: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'login-email', component: EmailComponent },
{ path: 'members', component: MembersComponent, canActivate: [AuthGuard] },
{ path: '', component: LoginComponent},
{ path: 'bookings', component: BookingsComponent },
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
mydash.routes.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AuthGuard } from '../auth.service';
import { MydashBookingsComponent } from '../mydash/mydash-bookings/mydash-bookings.component';
import { MydashChartComponent } from '../mydash/mydash-chart/mydash-chart.component';
import { MydashDashboardComponent } from '../mydash-dashboard/mydash-dashboard.component';
export const Dashboardrouter: Routes = [
{
path: 'dashboard',
children: [{
path: '',
pathMatch: 'full',
component: MydashDashboardComponent
},
{
path: 'mybookings',
component: MydashBookingsComponent
}]
}
];
export const DashboardRouting: ModuleWithProviders = RouterModule.forChild(Dashboardrouter);
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AngularFireModule } from 'angularfire2';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { EmailComponent } from './email/email.component';
import { SignupComponent } from './signup/signup.component';
import { MembersComponent } from './members/members.component';
import { AuthGuard } from './auth.service';
import { routes } from './app.routes';
import { IconsComponent } from './icons/icons.component';
import { NotificationsComponent } from './notifications/notifications.component';
import { UserComponent } from './user/user.component';
import { MydashModule } from './mydash/mydash.module';
import { HomeComponent } from './home/home.component';
import { BookingsComponent } from './bookings/bookings.component';
import {FirebaseServiceService} from './services/firebase-service.service';
// Must export the config
export const firebaseConfig = {
...
};
#NgModule({
declarations: [
AppComponent,
LoginComponent,
EmailComponent,
SignupComponent,
MembersComponent,
IconsComponent,
NotificationsComponent,
UserComponent,
HomeComponent,
BookingsComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig),
MydashModule,
routes,
],
providers: [AuthGuard,FirebaseServiceService],
bootstrap: [AppComponent],
})
export class AppModule { }
mydash.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { MydashChartComponent } from './mydash-chart/mydash-chart.component';
import { MydashCheckboxComponent } from './mydash-checkbox/mydash-checkbox.component';
import { MydashCloseLayerComponent } from './mydash-close-layer/mydash-close-layer.component';
import { MydashFooterComponent } from './mydash-footer/mydash-footer.component';
import { MydashNavbarComponent } from './mydash-navbar/mydash-navbar.component';
import { MydashSidebarComponent } from './mydash-sidebar/mydash-sidebar.component';
import { MydashSidebarItemsComponent } from './mydash-sidebar-items/mydash-sidebar-items.component';
import { MydashTableComponent } from './mydash-table/mydash-table.component';
import { MydashTaskListComponent } from './mydash-task-list/mydash-task-list.component';
import { MydashUserProfileComponent } from './mydash-user-profile/mydash-user-profile.component';
import { MydashNavbarItemsComponent } from './mydash-navbar-items/mydash-navbar-items.component';
import { MydashBookingsComponent } from './mydash-bookings/mydash-bookings.component';
import { DashboardRouting} from './mydash.routes';
import { MydashDashboardComponent } from '../mydash-dashboard/mydash-dashboard.component';
export interface DropdownLink {
title: string;
routerLink?: string;
}
export enum NavItemType {
Sidebar = 1, // Only ever shown on sidebar
NavbarLeft = 2, // Left-aligned icon-only link on navbar in desktop mode, shown above sidebar items on collapsed sidebar in mobile mode
NavbarRight = 3 // Right-aligned link on navbar in desktop mode, shown above sidebar items on collapsed sidebar in mobile mode
}
export interface NavItem {
type: NavItemType;
title: string;
routerLink?: string;
iconClass?: string;
numNotifications?: number;
dropdownItems?: (DropdownLink | 'separator')[];
}
#NgModule({
imports: [
CommonModule,
DashboardRouting,
],
declarations: [
MydashChartComponent,
MydashCheckboxComponent,
MydashCloseLayerComponent,
MydashFooterComponent,
MydashNavbarComponent,
MydashSidebarComponent,
MydashSidebarItemsComponent,
MydashTableComponent,
MydashTaskListComponent,
MydashUserProfileComponent,
MydashNavbarItemsComponent,
MydashBookingsComponent,
MydashDashboardComponent],
// These components are to export to allow access from the Dashboard. Do it manually, not done by ng CLI.
exports: [
MydashSidebarComponent,
MydashNavbarComponent,
MydashFooterComponent,
MydashChartComponent,
MydashTaskListComponent,
MydashTableComponent,
MydashUserProfileComponent,
MydashCloseLayerComponent,
MydashBookingsComponent
],
providers:[]
})
export class MydashModule { }
I solved the issue. The problem was because the dashboard component was missing in the file name mydash.routes.ts. I assigned the appropriate component underneath the path: 'dashboard', before the Child routes. Now, it works like a champ. Cheers!
The Answer code below.
path: 'dashboard',
component: MydashDashboardComponent,
children: [{

Routing when nested components are used on AppComponent

I am fairly new to Angular 2 and having a problem with Routing. I have just started to explore the Routing. I will explain the structure and what I have achieved so far,
app.router.ts
import { ModuleWithProviders } from '#angular/core'
import { Routes, RouterModule } from '#angular/router'
import { AppComponent } from './app.component';
import { LoginComponent } from "../app/login/login.component"
export const router: Routes = [
{ path: '', component: LoginComponent },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: AppComponent }
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import {UiSwitchModule} from 'angular2-ui-switch'
import { AppComponent } from './app.component';
import { AllReportsComponent } from "../app/all-reports/all-reports.component"
import { AvailableReportsComponent } from "../app/available-reports/available-reports.component"
import { NextReportsComponent } from "../app/next-reports/next-reports.component"
import { UrlsComponent } from "../app/urls/urls.component"
import { LoginComponent } from "../app/login/login.component"
import { TaskApi } from "../app/api/TaskApi"
import { routes } from "../app/app.router"
#NgModule({
imports: [
BrowserModule,
FormsModule,
UiSwitchModule,
HttpModule,
routes
],
declarations: [
AppComponent,
AllReportsComponent,
AvailableReportsComponent,
NextReportsComponent,
UrlsComponent,
LoginComponent
],
bootstrap: [AppComponent]
})
export class AppModule {
}
app.html
<div>
<all-reports></all-reports>
<available-reports></available-reports>
<next-reports></next-reports>
<urls></urls>
</div>
app.component.ts (very simple)
import { Component } from "#angular/core"
#Component({
templateUrl: '../app/app.html'
})
export class AppComponent {
}
and login.component.ts
import { Component } from '#angular/core';
import { TaskApi } from '../api/TaskApi';
import * as models from '../model/models';
#Component({
styleUrls: ['/app/css/login.css'],
templateUrl: '../../app/login/login.html',
providers: [TaskApi]
})
export class LoginComponent {
}
Now it can be seen that I am using multiple directives on app.html and all the respective components are working fine.
The problem I am facing is when I introduce Routing then I am able to understand where to use "router-outlet". I have used it on Index.html but it does not work and gives error about ng-component. So to just test around I have used following in Index.html,
<body>
<base href="/">
<ng-component></ng-component>
</body>
After I do this then my AppComponent is displayed by default where the LoginComponent should be displayed by default. On console, It also gives me error "Error: Cannot find primary outlet to load 'LoginComponent'"
Kindly guide me if I am using 4 directives on App.html as mentioned above then in that case how the routing will work. To summarize, I want to display Login page on localhost:3009/login and localhost:3009 and I want to display Home page (app.html) in localhost:3009/dashboard and app.html is using 4 directives to display 4 child components on it.
Angular Routing
Since Angular is single page application the routing functionality
helps to display different view in single page.
How to use router to change view?
since app.component.html is main view for most user. Iam also consider app.component.html as main view.
Router-outlet
Router-outer helps to load the change in our angular application.
app.component.html
<router-outlet></router-outlet>
Set AppComponent Default page as router-outlet and create new Dashboard.component.html in your main view.
router.ts
import { ModuleWithProviders } from '#angular/core'
import { Routes, RouterModule } from '#angular/router'
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard.component';
import { LoginComponent } from "../app/login/login.component"
export const router: Routes = [
{ path: '', component: LoginComponent },
{ path: 'login', redirectTo: '', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent }
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
The problem with your code is that there is no 'router-outlet', so angular doesn't understand where to display the view.
The 'router-outlet' directive marks where the router displays a view.
In your code, since in app.component.ts you are using app.html so you should use <router-outlet> </router-outlet> in that HTML file.
Your app.html file should look like this:
<router-outlet> </router-outlet>
These below things should not be used in the app component HTML file. They should be used in their the corresponding components.
<all-reports></all-reports>
<available-reports></available-reports>
<next-reports></next-reports>
<urls></urls>
For further understanding, please refer to the official documentation of Angular2. They have explained it pretty well here https://angular.io/docs/ts/latest/guide/router.html

Error while configuring routes in Angular 2

i have been working with a product list Project and while configuring routes to navigate between different views, I get a red squiggly under the '#Routes' decorator and when i hover over the Routes, it says 'Routes only refers to a type, but is being used as a value here'. I researched in so many sights including here and tried many different ways to resolve this but I could not find out the issue.
app.component.ts
import { Component } from '#angular/core';
import { ProductListComponent } from './products/product-list.Component';
import { ProductService } from './products/product.service'
import { Routes } from '#angular/router';
import 'rxjs/Rx'; // Load all features
import { WelcomeComponent } from './home/welcome.component'
#Component({
selector: 'pm-app',
template: `
<div>
<nav class='navbar navbar-default'>
<div class='container-fluid'>
<a class='navbar-brand'>{{pageTitle}}</a>
<ul class='nav navbar-nav'>
<li><a>Home</a></li>
<li><a>Product List</a></li>
</ul>
</div>
</nav>
</div>
` ,
entryComponents : [ProductListComponent],
providers: [ProductService]
})
#Routes([
{ path: '/welcome' , name: 'Welcome' , component: WelcomeComponent, useAsDefault: true},
{ path: '/products' , name: 'Products' , component: ProductListComponent }
])
export class AppComponent {
pageTitle:string = 'Acme Product Management';
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { ProductListComponent } from './products/product-list.Component';
import { HttpModule } from "#angular/http";
import { RouterModule } from '#angular/router'
import { ProductFilterPipe } from './products/product-filter.pipe';
import { StarComponent } from './shared/star.component';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule,FormsModule,HttpModule,RouterModule],
declarations: [ AppComponent,ProductListComponent,ProductFilterPipe,StarComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
welcome.compnent.ts
import { Component } from '#angular/core';
#Component({
templateUrl: 'app/home/welcome.component.html'
})
export class WelcomeComponent {
public pageTitle: string = 'Welcome';
}
I think my coding is fine. But unable to get the expected result. Please Help!
Found out, the issue is... with RC5, Routes is an array of path's & is no more a Decorator, and you have to import 'RouterModule' instead of 'provideRouter'. While exporting you have to use 'RouterModule.forRoot'.
Also with RC5, we no longer specify the string name of the component while configuring routes instead we only specify the path & component only. And we no longer use the prefix '/' for the path. Also we no longer using useAsDefault instead we use redirectTo property to configure the default path.
I have used a separate module to do my route configurations instead of doing it in the root component as earlier. An updated version of my route configuration is given as below. Hope this will be helpful.
app.routes.ts
import { Routes, RouterModule } from '#angular/router';
import { ProductListComponent } from './products/product-list.Component';
import { WelcomeComponent } from './home/welcome.component'
import { ProductDetailComponent } from './products/product- detail.component';
const routes: Routes = [
{
path: 'welcome' ,
component: WelcomeComponent,
},
{
path: 'products' ,
component: ProductListComponent
},
{
path: 'product/:id' ,
component: ProductDetailComponent
},
{
path:'',
redirectTo:'/welcome',
pathMatch:'full'
},
];
export const routing = RouterModule.forRoot(routes);

Refreshing the angular 2 application is generating Error 404 - Page not found exception

I am developing Angular 2 application that is using KendoUI datagrid in asp.net web application. I have set index.html as the startup page. When i press F5, index.html loads. Click on the Risks Menu displays the datagrid with data that is defined in risk-list.component.html page. Its URL is localhost/risks. If I press F5, I get 404 page not found error. Could somebody tell me what the problem could be and how can I fix it?
This is my code:
risk-list.Component.ts
import { Component, OnInit } from '#angular/core';
import { Risk } from './risk';
import { RiskService } from './risk.service';
#Component({
moduleId: module.id,
selector: 'rm-risks',
templateUrl: '/app/risk-list.component.html',
providers: [RiskService]
})
export class RiskListComponent implements OnInit {
title = 'Risk List';
risks: Risk[];
constructor(private _riskService: RiskService) {
console.log(this.risks);
}
getRisks(): void {
this._riskService.getRisks().then(risks => this.risks = risks);
}
ngOnInit(): void {
this.getRisks();
}
};
risk-list.component.html
<kendo-grid [data]="risks">
<kendo-grid-column field="reference" title="Reference" width="120">
</kendo-grid-column>
<kendo-grid-column field="insuredName" title="Insured Name">
</kendo-grid-column>
<kendo-grid-column field="inceptionDate" title="Inception Date" width="230">
</kendo-grid-column>
<kendo-grid-column field="riskType" title="Risk Type" width="120">
</kendo-grid-column>
<kendo-grid-column field="Status" title="Status">
</kendo-grid-column>
<kendo-grid-column field="grossPremium" title="Gross Premium" width="230">
</kendo-grid-column>
<kendo-grid-column field="allocatedTo" title="Allocated To" width="120">
</kendo-grid-column>
<kendo-grid-column field="allocatedCompany" title="Allocated Company">
</kendo-grid-column>
<kendo-grid-column field="Discontinued" width="120">
<template kendoCellTemplate let-dataItem>
<input type="checkbox" [checked]="dataItem.Discontinued" disabled />
</template>
</kendo-grid-column>
</kendo-grid>
risk.service.ts
import { Injectable } from '#angular/core';
import { Risk } from './risk';
import { Risks } from './mock-risk';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
#Injectable()
export class RiskService {
getRisks(): Promise<Risk[]> {
return Promise.resolve(Risks);
}
}
risk.ts
export class Risk {
riskId: number;
reference: string;
insuredName: string;
inceptionDate: string;
riskType: string;
status: string;
grossPremium: number;
allocatedTo: string;
allocatedCompany: string;
}
mock-risk.ts
import { Risk } from './risk'
export const Risks: Risk[] = [
{
"riskId": 1,
"reference": "HISC9308336",
"insuredName": "SA 84161",
"inceptionDate": "March 19, 2016",
"riskType": "Quote",
"status": "Indication",
"grossPremium": 100,
"allocatedTo": "Broker User",
"allocatedCompany": "Broker"
},
{
riskId: 2,
reference: "HISC9308337",
insuredName: "SA 84161",
inceptionDate: 'April 22, 2016',
riskType: 'Quote',
status: 'Indication',
grossPremium: 300,
allocatedTo: 'Broker User',
allocatedCompany: 'Broker'
}
];
risks.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { RiskListComponent } from './risk-list.component';
import { RiskService } from './risk.service';
import { RiskRoutingModule } from './risks-routing.module';
import { GridModule } from '#progress/kendo-angular-grid';
#NgModule({
imports: [
CommonModule,
FormsModule,
RiskRoutingModule,
GridModule
],
declarations: [
RiskListComponent
],
providers: [
RiskService
]
})
export class RisksModule { }
risks-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { RiskListComponent } from './risk-list.component';
#NgModule({
imports: [
RouterModule.forChild([
{ path: 'risks', component: RiskListComponent }
])
],
exports: [
RouterModule
]
})
export class RiskRoutingModule { }
app.component.html
<h1>Angular Router</h1>
<nav>
<a routerLink="/risks" routerLinkActive="active">Risks</a>
</nav>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '#angular/core';
#Component({
moduleId: module.id,
selector: 'my-app',
templateUrl:'/app/app.component.html'
})
export class AppComponent { }
app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { RiskListComponent } from './risk-list.component'
import { HomeComponent } from './home.component'
#NgModule({
imports: [
RouterModule.forRoot([
{ path: '', component: HomeComponent }
])
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
main.ts
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
This problem is solved by implementing HashLocationStrategy which adds # to all your routes. For example, http://localhost/myComponent becomes http://localhost/#/myComponent. You achieve this by adding HashLocationStrategy to AppModule's providers:
{ provide: LocationStrategy, useClass: HashLocationStrategy }
Of course, you need to import LocationStrategy and HashLocationStrategy from #angular/common:
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
For more information, check Angular 2 Router & Navigation - Browser URL Styles.
When the browser is refreshed it will send a get request to the server with the current url, since angular is using HTML 5 style navigation, the url will make no sense to the server. Either update your server to serve the index.html on particular paths or use the HashLocationStrategy.
The benefit of using HTML 5 style navigation is that you can mix your angular app with server rendered pages.
An example of getting this working with asp.net: http://blog.johnnyreilly.com/2015/05/a-tale-of-angular-html5mode-aspnet-mvc.html
More reading on angular: https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles
The best way to get rid of this Error404 page not found, you should import HashLocationStrategy to appModule.ts
When I previously worked on Angular, Same type of error raised in my Project, so that I created a simple repository for this kind of error (404 Page Not Found), it may help you. Here is the link -> AngularAppExample

Resources