ionic runtime error - zone already loaded - firebase

I just wanted to use ionic 3 + firebase authentication. I followed the latest guidelines, youtube, documentation but i always encountered this problem when running 'ionic serve':
Error: Zone already loaded.
at http://localhost:8100/build/vendor.js:117672:15
at http://localhost:8100/build/vendor.js:118284:3
at FUNCTION (http://localhost:8100/build/vendor.js:117649:10)
at Object.<anonymous> (http://localhost:8100/build/vendor.js:117652:2)
at Object.<anonymous> (http://localhost:8100/build/vendor.js:120702:30)
at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
at Object.defineProperty.value (http://localhost:8100/build/vendor.js:69145:66)
at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
at Object.<anonymous> (http://localhost:8100/build/vendor.js:117167:72)
at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
Ionic Framework: 3.9.2
Ionic App Scripts: 3.1.9
Angular Core: 5.2.10
Angular Compiler CLI: 5.2.10
Node: 9.11.1
OS Platform: Windows 8.1
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
I have searched everything but nothing helps.
Thing i already did:
I follow everything from this link "Runtime Error Zone already loaded" in ionic 3 but it didn't solve my problem
I tried to remove 'import zone..' but could not find it. Searched the entire files but could not fine import zone. I got from this link How do I determine what zone is already loaded?
I could not find any solutions right now. Any suggestions given are appreciated.
My app.module.ts file
import { RegisterPage } from './../pages/register/register';
import { LoginPage } from './../pages/login/login';
import { CollectionPage } from './../pages/collection/collection';
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
const firebaseAuth = {
apiKey: "Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "fxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
databaseURL: "hxxxxxxxxxxxxxx",
projectId: "fxxxxxxxxxxxxx",
storageBucket: "firxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxx"
};
#NgModule({
declarations: [
MyApp,
HomePage,
CollectionPage,
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(firebaseAuth),
AngularFireAuthModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
CollectionPage,
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {
}
My register.html file
<ion-header>
<ion-navbar>
<ion-title>Register</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label>Username</ion-label>
<ion-input type="text" value=""></ion-input>
</ion-item>
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" value=""></ion-input>
</ion-item>
</ion-list>
<div padding>
<button ion-button color="primary" block (click)="registerUser()">Register</button>
</div>
</ion-content>
My register.ts file
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
#IonicPage()
#Component({
selector: 'page-register',
templateUrl: 'register.html',
})
export class RegisterPage {
#ViewChild('username') user;
#ViewChild('password') password;
constructor(private fire: AngularFireAuth, public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad RegisterPage');
}
registerUser() {
this.fire.auth.createUserWithEmailAndPassword(this.user.value, this.password.value)
.then(data => {
console.log('got data ', data);
})
.catch(error => {
console.log('got an error ', error);
});
console.log('Would register user with ', this.user.value, this.password.value);
}
}

I had the exact problem today. It proves a problem of angularfire2
You can find the issue on github: Runtime Error Zone already loaded
Once I rollback to rc4, everything works properly, hope it helps.
npm install angularfire2#5.0.0-rc.4

Related

JWT Module can't compile

After adding a few lines of code I described below appears
I have a problem, when I try to compile Angular, I have this error:
ERROR in node_modules/#auth0/angular-jwt/index.d.ts:29:48 - error NG6005: JwtModule.forRoot returns a ModuleWithProviders type without a generic type argument. Please add a generic type argument to the ModuleWithProviders type. If this occurrence is in library code you don't control, please contact the library authors.
29 static forRoot(options: JwtModuleOptions): ModuleWithProviders;
~~~~~~~~~~~~~~~~~~~
src/app/app.component.html:9:1 - error NG8001: 'app-nav' is not a known element:
1. If 'app-nav' is an Angular component, then verify that it is part of this module.
2. If 'app-nav' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
9 <app-nav></app-nav>
~~~~~~~~~~~~~~~~~~~
src/app/app.component.ts:8:16
8 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
src/app/app.component.html:10:1 - error NG8001: 'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
10 <router-outlet></router-outlet>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/app.component.ts:8:16
8 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
src/app/nav/nav.component.html:3:33 - error NG8002: Can't bind to 'routerLink' since it isn't a known property of 'a'.
3 <a class="navbar-brand" [routerLink]="['/home']">Dating App</a>
~~~~~~~~~~~~~~~~~~~~~~~~
src/app/nav/nav.component.ts:8:16
8 templateUrl: './nav.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component NavComponent.
src/app/register/register.component.html:6:74 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.
6 <input type="text" class="form-control" required name="username" [(ngModel)]="model.username" placeholder="Username">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
src/app/register/register.component.html:11:78 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.
11 <input type="password" class="form-control" required name="password" [(ngModel)]="model.password" placeholder="Password">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
src/app/register/register.component.html:1:22 - error NG8003: No directive found with exportAs 'ngForm'.
1 <form #registerForm="ngForm" (ngSubmit)="register()">
~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
this i my index.d.ts
import { ModuleWithProviders, Provider } from '#angular/core';
export * from './src/jwt.interceptor';
export * from './src/jwthelper.service';
export * from './src/jwtoptions.token';
export interface JwtModuleOptions {
jwtOptionsProvider?: Provider;
config?: {
tokenGetter?: () => string | null | Promise<string | null>;
headerName?: string;
authScheme?: string;
whitelistedDomains?: Array<string | RegExp>;
blacklistedRoutes?: Array<string | RegExp>;
throwNoTokenError?: boolean;
skipWhenExpired?: boolean;
};
}
declare module "#angular/core" {
interface ModuleWithProviders<T = any> {
ngModule: Type<T>;
providers?: Provider[];
}
}
export declare class JwtModule {
constructor(parentModule: JwtModule);
static forRoot(options: JwtModuleOptions): ModuleWithProviders;
}
//# sourceMappingURL=index.d.ts.map
this is my app.module.ts:
import { MemberCardComponent } from './members/member-card/member-card.component';
import { appRoutes } from './routes';
import { ErrorInterceptorProvider } from './_services/error.interceptor';
import { AuthService } from './_services/auth.service';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {HttpClientModule} from '#angular/common/http';
import {FormsModule, } from '#angular/forms';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { RouterModule } from '#angular/router';
import { JwtModule } from '#auth0/angular-jwt';
import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';
import { RegisterComponent } from './register/register.component';
import { HomeComponent } from './home/home.component';
import { MemberListComponent } from './members/member-list/member-list.component';
import { ListsComponent } from './lists/lists.component';
import { MessagesComponent } from './messages/messages.component';
// tslint:disable-next-line:typedef
export function tokenGetter(){
return localStorage.getItem('token');
}
#NgModule({
declarations: [
AppComponent,
NavComponent,
RegisterComponent,
HomeComponent,
MemberListComponent,
ListsComponent,
MessagesComponent,
MemberCardComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
BsDropdownModule.forRoot(),
RouterModule.forRoot(appRoutes),
JwtModule.forRoot({
config: {
// tslint:disable-next-line:object-literal-shorthand
tokenGetter: tokenGetter,
whitelistedDomains: ['localhost:5000'],
blacklistedRoutes: ['localhost:5000/api/auth']
}
}),
],
providers: [
AuthService,
ErrorInterceptorProvider
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Tt only adds that to app.module.ts:
// tslint:disable-next-line:typedef
export function tokenGetter(){
return localStorage.getItem('token');
}
and
JwtModule.forRoot({
config: {
// tslint:disable-next-line:object-literal-shorthand
tokenGetter: tokenGetter,
whitelistedDomains: ['localhost:5000'],
blacklistedRoutes: ['localhost:5000/api/auth']
}
}),
As I add this JWT module and try to add it to the project file I can't compile it if the problem is with the Angular version or it's something else.
I can't compile my program, How can I solve this problem.;/

API data is not getting at first loading ionic2, angular2

I am struggling from last couple days.I am using ionic2/3 angular 2 and wordpress for data.
I am trying to load categories data at home page at first load but i am not getting. In browser it's coming properly and also when i click on menu button entire data is showing properly. I checked all blogs but didn't get any proper solution.
Please help me if any one had same issues and solved.Thanks in advance.
I am attaching my codes here.
enter code here
Home.ts-
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
woocommerce: any;
categories: any[];
// Home=HomePage;
constructor(public navCtrl: NavController) {
this.categories=[];
}
ionViewDidLoad(){
this.getCatData();
}
getCatData(){
this.woocommerce = WC({
url:'http://www.example.com/',
consumerKey: 'ck_7dfe0aec65ahgcdhgcdhcdhf36288d1fa2e4c01',
consumerSecret: 'cs_da53e5b228eb6235bshhcskhc7a68541ad809743'
});
this.woocommerce.getAsync("products/categories").then((data)=>{
console.log(JSON.parse(data.body).product_categories);
this.categories = JSON.parse(data.body).product_categories;
},(err)=>{
console.log(err);
})
}
}
Home.html-
<ion-header>
<ion-navbar color="header">
<ion-buttons left>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
</ion-buttons>
<ion-buttons right>
<button ion-button icon-only>
<ion-icon name="search"></ion-icon>
</button>
</ion-buttons>
<ion-title>
KAAIROS EXPORTS
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<!-- slider -->
<ion-card>
<ion-slides loop="true" autoplay="false" pager>
<ion-slide *ngFor= "let number of [1,2,3,4,5]"><img src="./assets/img/{{number}}.jpg"/></ion-slide>
</ion-slides>
</ion-card>
<!-- end-slider -->
<!-- <ion-grid> Hi this is second line
</ion-grid> -->
<ion-item *ngFor="let category of categories">
<h2> {{ category.name }} </h2>
</ion-item>
</ion-content>
app.component.ts-
import { TabsPage } from './../pages/tabs/tabs';
import { HomePage } from './../pages/home/home';
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
//import { Menu } from '../pages/menu/menu';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
// rootPage: any = Menu;
rootPage = TabsPage;
constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
// go_to_home(){
// this.nav.setRoot(HomePage);
// }
}
app.html-
<ion-menu side="left" [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<!-- <ion-list>
<!-- <ion-item (click)="go_to_home()" menuClose>
Home
</ion-item> -->
<!-- <ion-item (click)="go_to_about()" menuClose>
About
</ion-item> -->
<!-- <ion-item (click)="go_to_contact()" menuClose>
Contact Us
<!-- </ion-item> -->
</ion-content>
</ion-menu>
<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="true"></ion-nav>
app.module:-
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { AboutusPage } from '../pages/aboutus/aboutus';
import { ContactusPage } from '../pages/contactus/contactus';
import { CategoryPage } from '../pages/category/category';
import { ProductsByCategoryPage } from '../pages/products-by-category/products-by-category';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { WooCommerceProvider } from '../providers/woocommerce/woocommerce';
import { HttpModule } from '#angular/http';
#NgModule({
declarations: [
MyApp,
HomePage,
TabsPage,
AboutusPage,
ContactusPage,
CategoryPage,
//ProductListPage,
ProductsByCategoryPage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp,{
mode:'ios'
}),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
TabsPage,
AboutusPage,
ContactusPage,
CategoryPage,
ProductsByCategoryPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
WooCommerceProvider
]
})
export class AppModule {}
Simply call the ChangeDetectorRef after successfull API call to refresh the changes in UI. PFB the sample code where we have triggered change detector on subscribe call. You can check the working version here
import { Component, ViewChild, ChangeDetectorRef } from '#angular/core';
import { NavController, Content } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
#ViewChild(Content) content: Content;
Arr = Array; //Array type captured in a variable
num:number = 1000;
toolbar_color: string;
constructor(public navCtrl: NavController, public ref : ChangeDetectorRef) {
this.toolbar_color="secondary";
}
changeColor(){
this.toolbar_color="primary";
this.ref.detectChanges();
}
ionViewDidLoad() {
//this.content.enableJsScroll();
this.content.ionScrollEnd.subscribe(() => {
this.changeColor();
});
}
}
This is because your data is asynchronously loaded. The view has already been rendered by the time your data arrives.
One way to fix this is to add some kind of "refresh" method and call it when you receive the data (e.g., in .getAsync().then(...)).

Property 'login' does not exist on type 'AngularFireAuth' ionic

Iam trying to create a login page using firebase in ionic.I have imported al the neccessary componenets but i get the error Property 'login' does not exist on type 'AngularFireAuth' in the login method. Please help!
login.ts
import { Component } from '#angular/core';
import { NavController, NavParams, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireAuth } from 'angularfire2/auth';
#Component({
selector:'page-login',
templateUrl:'login.html'
})
export class LoginPage{
email: any;
password: any;
constructor(public NavCtrl: NavController,public NavParams,public angfire: AngularFireAuth){
}
ionViewDidLoad(){
console.log('ionViewDidload LoginPage');
}
login(){
this.angfire.login({
email:this.angfire,
password:this.password
},
})
}
}
For AngularFire2 try this
signInWithFacebook() {
this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider())
.then(res => console.log(res));
}

firebase.auth().onAuthStateChanged No provider for AngularFire

I get the error
Uncaught (in promise): Error: No provider for AngularFire!
When I tried to call firebase.auth().onAuthStateChanged.
Don't know why this happens. Please help.
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
import { Login } from '../pages/login/login';
import firebase from 'firebase';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = Login;
isAuthenticated = false;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
firebase.initializeApp({
apiKey: "AIzaSyC94rD8wXG0aRLTcG29qVGw8CFfvCK7XVQ",
authDomain: "myfirstfirebaseproject-6da6c.firebaseapp.com",
});
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.isAuthenticated = true;
this.rootPage = HomePage;
} else {
this.isAuthenticated = false;
this.rootPage = Login;
}
});
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
}
Your config isn't set up properly. You should have this code in your app.module.ts, not in your component.
import {
AngularFireModule,
AuthMethods,
AuthProviders
} from 'angularfire2';
...
#NgModule({
bootstrap: [AppComponent],
declarations: [AppComponent],
imports: [
AngularFireModule.initializeApp({
apiKey: '<some-key>',
authDomain: '<some-project-authdomain>',
databaseURL: '<some-database-URL>',
storageBucket: '<some-storage-bucket>'
}, {
method: AuthMethods.Password,
provider: AuthProviders.Password
}),
BrowserModule,
...
]
})
class AppModule {}
platformBrowserDynamic().bootstrapModule(AppModule);
This is where you should have the above code. If you don't have the provider set, you'll keep getting the error.

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