Angular Service called twice in lazy loaded modules - javascript

I am creating an Angular application where I have implemented lazy loading. It is working fine but when ever I am making any HTTP request to the server the action is happening twice.
In my current structure I have created a shared module to store all the common modules and components. I am using ajax service to make all the api calls to backend, AuthTokenService is to store and handle Authentication token-
Feature Module -
import { NgModule, ModuleWithProviders } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import { ReactiveFormsModule, FormsModule } from '#angular/forms';
//Importing HTTP Intercepter and services
import { HTTPInterceptorProvider } from '#/core/_HTTP-interceptor';
import { AjaxService, AuthTokenService } from '#/core/_services';
//Importing pipes
import { SummaryPipe } from '#/core/_pipes';
//Externel Plugins Modules
import { NgSelectModule } from '#ng-select/ng-select';
import { AnimatedNumbersComponent } from '#/modules/shared';
#NgModule({
declarations: [
AnimatedNumbersComponent,
//Pipes used are listed here
SummaryPipe
],
imports: [
CommonModule,
ReactiveFormsModule,
FormsModule,
RouterModule,
NgSelectModule
],
providers: [
],
exports: [
AnimatedNumbersComponent,
ReactiveFormsModule,
FormsModule,
NgSelectModule
]
})
export class FeatureModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [
AjaxService,
AuthTokenService,
HTTPInterceptorProvider
]
};
}
}
App Module -
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations'
import { FeatureModule } from './modules/featured/feature.module'
import { DatePipe } from '#angular/common';
import { NgxSpinnerModule } from "ngx-spinner";
import { AppComponent } from '#/app.component';
#NgModule({
declarations: [
AppComponent,
routingComponents
],
imports: [
HttpClientModule,
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
NgxSpinnerModule, // NGX Spinner
FeatureModule.forRoot()
],
providers: [
DatePipe
],
bootstrap: [AppComponent]
})
export class AppModule { }
App Routing Module -
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AuthGuard, SecureOuterPagesGuard, SecureInnerPagesGuard } from "#/core/_guards";
// Home page of the application
import { IndexComponent } from '#/modules/index/index.component';
import {
LoginComponent,
RegisterComponent,
ForgetPasswordComponent,
ResetPasswordComponent
} from '#/modules/auth';
import {
PageNotFoundComponent,
InternalServerErrorComponent
} from '#/modules/shared';
const routes: Routes = [
{
path: '',
component: IndexComponent
},
{
path: 'login',
component: LoginComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'register',
component: RegisterComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'forget-password',
component: ForgetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'reset-password',
component: ResetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'dashboard',
loadChildren: () => import('./modules/dashboard/dashboard.module').then(m => m.DashboardModule),
canActivate: [AuthGuard]
},
{
path: 'internal-server-error',
component: InternalServerErrorComponent
},
{
path: '**',
component: PageNotFoundComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class AppRoutingModule { }
export const routingComponents = [
IndexComponent,
LoginComponent,
RegisterComponent,
ForgetPasswordComponent,
ResetPasswordComponent,
SessionTimeOutComponent,
PageNotFoundComponent
]
Ajax Service -
import { Injectable } from '#angular/core';
import { environment } from '../../../environments/environment';
import { HttpClient, HttpResponse } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map, timeout } from "rxjs/operators";
#Injectable()
export class AjaxService {
constructor(
private _http: HttpClient,
) { }
apiCall(
data: any,
url: any,
method: 'DELETE' | 'GET' | 'HEAD' | 'POST' | 'JSONP' | 'PUT',
isRawUrlFormat: boolean = false
){
// Checking if the provide url is in raw format or not
if (isRawUrlFormat == false) {
url = environment.API_URL + "/" + url;
}
// creating request variable of type Observable so that any component can subscribe it
let request: Observable<any>;
// setting methods of request type and passing params (url, data, headeers and observe to access complete response)
switch (method) {
case 'GET':
request = this._http.get(url, { observe: 'response' });
break;
case 'POST':
request = this._http.post(url, data, { observe: 'response' });
break;
case 'PUT':
request = this._http.put(url, data, { observe: 'response' });
break;
default:
request = this._http.request(method, url, { observe: 'response' });
}
// returning api result with status, if found any error returns that error
return request.pipe(
timeout(environment.AJAX_TIMEOUT),
map((apiResult : HttpResponse<any>) => {
const status : number = apiResult.status;
let responseObject = apiResult.body;
responseObject.status = status;
// if found status 202 means has a refreshtoken in response then again setting it in localstorage
if (status == 202) {
localStorage.setItem("userToken", apiResult.body.response.data.token);
}
return responseObject;
})
)
}
}

Related

NullInjectorError: StaticInjectorError(i)[s -> e] : Angular 8

I am creating an Angular Application and I have used lazy Loading. When I am serving the application using ng serve --aot there is no error in the and also when I do ng build --prod still there is no error. But When I upload the build files in my hosting and trying to navigate from HOMEPAGE (https://pawsticks.rahuls.co.in) to LOGIN (https://pawsticks.rahuls.co.in/login) page there is an error in the terminal shows -
Uncaught (in promise): NullInjectorError: StaticInjectorError(i)[s -> e]:
StaticInjectorError(Platform: core)[s -> e]:
NullInjectorError: No provider for e!.
I am not getting it from where the error is occurring.
APP Module -
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { HttpClientModule } from '#angular/common/http';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations'
import { DatePipe } from '#angular/common';
import { FeatureModule } from '#/modules/featured';
import { NgxSpinnerModule } from "ngx-spinner";
import { AppComponent } from '#/app.component';
#NgModule({
declarations: [
AppComponent,
routingComponents
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
NgxSpinnerModule, // NGX Spinner
FeatureModule.forRoot() //Injecting Feature Module as ROOT Module
],
providers: [
DatePipe
],
bootstrap: [AppComponent]
})
export class AppModule { }
Feature Module:
import { NgModule, ModuleWithProviders } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import { ReactiveFormsModule, FormsModule } from '#angular/forms';
//Importing HTTP Intercepter and services
import { HTTPInterceptorProvider } from '#/core/_HTTP-interceptor';
import { AjaxService, AuthTokenService, CommonHelperService } from '#/core/_services';
import { SummaryPipe } from '#/core/_pipes';
//Externel Plugins Modules
import { ShowHidePasswordModule } from 'ngx-show-hide-password';
import { NgxIntlTelInputModule } from 'ngx-intl-tel-input';
import { ImageCropperModule } from 'ngx-image-cropper';
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { NgSelectModule } from '#ng-select/ng-select';
import { NgxPaginationModule } from 'ngx-pagination';
//Success Error Component, Password Strength Component, Animated Numbers Component
import {
SuccessErrorComponent,
PasswordStrengthBarComponent,
AnimatedNumbersComponent,
} from '#/modules/shared';
#NgModule({
declarations: [
SuccessErrorComponent,
PasswordStrengthBarComponent,
AnimatedNumbersComponent,
//Pipes used are listed here
SummaryPipe
],
imports: [
CommonModule,
ReactiveFormsModule,
FormsModule,
RouterModule,
NgxIntlTelInputModule,
ShowHidePasswordModule, // Show Hide Password Plugin Import
ImageCropperModule, // Image cropper Module
BsDatepickerModule.forRoot(), //Bootstrap Datepicker Plugin
BsDropdownModule.forRoot(),
NgSelectModule,
NgxPaginationModule
],
providers: [
],
exports: [
SuccessErrorComponent,
PasswordStrengthBarComponent,
AnimatedNumbersComponent,
SummaryPipe,
ReactiveFormsModule,
FormsModule,
NgxIntlTelInputModule,
ImageCropperModule, // Image cropper Module
BsDatepickerModule, //Bootstrap Datepicker Plugin
BsDropdownModule,
NgSelectModule,
NgxPaginationModule,
ShowHidePasswordModule
]
})
export class FeatureModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [
HTTPInterceptorProvider,
AjaxService,
AuthTokenService,
CommonHelperService
]
};
}
}
App Routing Module :
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { CustomPreloadingStrategy } from './preloading-strategy';
import { AuthGuard, SecureOuterPagesGuard } from "#/core/_guards";
// Home page of the application
import { IndexComponent } from '#/modules/index/index.component';
// Authentication and Authorization Components
import {
LoginComponent,
RegisterComponent,
VerifyAccountComponent,
VerifyAccountStatusComponent,
ForgetPasswordComponent,
ResetPasswordComponent
} from '#/modules/auth';
// Session Timeout, Page Not Found and Interner Server Error Components
import {
SessionTimeOutComponent,
PageNotFoundComponent,
InternalServerErrorComponent
} from '#/modules/shared';
const routes: Routes = [
{
path: '',
component: IndexComponent
},
{
path: 'login',
component: LoginComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'register',
component: RegisterComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'verify-account',
component: VerifyAccountComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'verify-account-status',
component: VerifyAccountStatusComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'forget-password',
component: ForgetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'reset-password',
component: ResetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'dashboard',
loadChildren: () => import('./modules/dashboard/dashboard.module').then(m => m.DashboardModule),
canActivate: [AuthGuard],
data: { preload: true }
},
{
path: 'internal-server-error',
component: InternalServerErrorComponent
},
{
path: 'page-not-found',
component: PageNotFoundComponent
},
{
path: 'session-time-out',
component: SessionTimeOutComponent
},
{
path: '**',
component: PageNotFoundComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy })],
exports: [RouterModule],
providers: [CustomPreloadingStrategy]
})
export class AppRoutingModule { }
export const routingComponents = [
IndexComponent,
LoginComponent,
RegisterComponent,
VerifyAccountComponent,
VerifyAccountStatusComponent,
ForgetPasswordComponent,
ResetPasswordComponent,
SessionTimeOutComponent,
PageNotFoundComponent,
InternalServerErrorComponent,
]

How to prevent losing data when navigating in angular?

I want to store array of items in a service (called cart service) and show it in component (cart.component.ts).
but the items are chosen each alone by the component bgview.component.ts that is a children of component single.component.ts that receive the items through http requests.
when i open the cart component i receive an empty array.
can i store these items in the service without losing them when navigating.
i've tried the following steps:
The component that i want to send items from :
export class BgviewComponent implements OnInit {
#Input() item: Item;
constructor(private cartservice: CartService) { }
ngOnInit() {
}
onAddToCart(){
this.cartservice.items.push(this.item);
}
}
the service :
#Injectable({
providedIn: 'root',
})
export class CartService {
public items: Item[]=[];
}
the receiving component:
export class CartComponent implements OnInit {
items: Item[]=[];
constructor(private cartservice:CartService) {
}
ngOnInit() {
this.items = this.cartservice.items;
console.log(this.items) //gives empty array
}
}
routing way:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeModule } from './pages/home/home.module';
import { ContactusModule } from './pages/contactus/contactus.module';
import { SingleModule } from './pages/single/single.module';
import { LoginModule } from './pages/login/login.module';
import { SearchpModule } from './pages/searchp/searchp.module';
import { AdminModule } from './pages/admin/admin.module';
import { FindpModule } from './pages/findp/findp.module';
import { AuthGuardService } from './services/auth.service';
import { CartModule } from './pages/cart/cart.module';
const routes: Routes = [
{
path: '',
loadChildren: () => HomeModule,
},
{
path: 'contact',
loadChildren: () => ContactusModule,
},
{
path: 'single/:id',
loadChildren: () => SingleModule,
},
{
path: 'login',
loadChildren: () => LoginModule,
},
{
path: 'searchp/:id',
loadChildren: () => SearchpModule,
},
{
path: 'login/admin',
loadChildren: () => AdminModule, canActivate: [AuthGuardService]
},
{
path: 'cart',
loadChildren: () => CartModule,
},
{
path: 'findp/:str',
loadChildren: () => FindpModule,
},
]
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
cart module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { CartComponent } from './cart.component';
import { CartRoutingModule } from './cart-routing.module';
import { CartService } from 'src/app/services/cart.service';
#NgModule({
declarations: [ CartComponent],
imports: [
CommonModule,
CartRoutingModule,
],
providers:[
]
})
export class CartModule { }
single module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { SingleComponent } from './single.component';
import { SharedModule } from 'src/app/shared/shared.module';
import { SingleRoutingModule } from './single-routing.module';
import { BgviewComponent } from './bgview/bgview.component';
import { HttpService } from 'src/app/services/http.service';
import { CartService } from 'src/app/services/cart.service';
#NgModule({
declarations: [SingleComponent, BgviewComponent],
imports: [
CommonModule,
SharedModule,
SingleRoutingModule,
],
providers:[
HttpService,
]
})
export class SingleModule { }
please help me i'm stuck here.
Also make sure that onAddToCart method is called.
You can simply add some log message inside method to check it.
Make sure that the onAddToCArt method is called.

Angular router error - Invalid configuration of route

Using angular 4, I am redirecting the route with an empty path to navbar component. So I have added pathMatch: full and I placed this entry at the top in routes array.
But I still get the following error:
zone.js:522 Unhandled Promise rejection:
Invalid configuration of route '': Array cannot be specified ;
Zone: root ;
Task: Promise.then ;
Value: ZoneAwareError {
__zone_symbol__error: Error: Invalid configuration of route '': Array
cannot be specified
at Zone.run (http://localhost:4200/polyfills.bundle.js:6405:43) [ => angular]
route.component.ts
import {Route} from '#angular/router';
import { AppComponent } from './app.component';
import {NavbarComponent} from './navbar/navbar.component';
import {RegistrationComponent} from './registration/registration.component';
export const appRoutes:Route =[
{
path: '',
redirectTo: 'navbar',
pathMatch: 'full'
}, {
path: 'home',
component: NavbarComponent
}, {
path: 'navbar',
component: NavbarComponent
}, {
path: 'registration',
component: RegistrationComponent
}
];
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 { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import {NavbarComponent} from './navbar/navbar.component';
import {RegistrationComponent} from './registration/registration.component';
import { appRoutes } from './app.route';
#NgModule({
declarations: [
AppComponent,
NavbarComponent,
RegistrationComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([appRoutes])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Just change
From
RouterModule.forRoot([appRoutes])
To
RouterModule.forRoot(appRoutes)
export const appRoutes: Route[] = [
instead of
export const appRoutes:Route =[

Uncaught TypeError: Cannot read property 'prototype' of undefined at __extends (Subscriber.js:5)

I got this error after ng build and uploading to production server. I'm using angular cli on angular4. All this really started when I added the Route Guard to a feature module. I reverted back to when I had no Guard but the error still persists. When I run ng serve on my local machine I don't get this error.
This is my app module:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { HashLocationStrategy, LocationStrategy } from '#angular/common';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
/* Routing Module */
import { AppRoutingModule } from './app-routing.module';
/* Authentication */
import {AuthenticateService} from './authenticate.service';
import {AuthGuard} from './auth.guard';
import {DashboardModule} from './dashboard/dashboard.module';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
DashboardModule,
AppRoutingModule
],
providers: [
{ provide: LocationStrategy, useClass: HashLocationStrategy},
AuthenticateService,
AuthGuard
],
bootstrap: [AppComponent]
})
export class AppModule { }
My auth Service:
import { Injectable } from '#angular/core';
import {Response, Headers, Http, RequestOptionsArgs} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class AuthenticateService {
baseUrl = 'myurl/public';
constructor(private http: Http) { }
register(form) {
return this.http.post(`${this.baseUrl}/register`, form)
.map((response: Response) => {
const user = response.json();
if (user.status) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('loggedUser', JSON.stringify(user));
}
return user;
})
.catch((error: any) => Observable.throw(error.json().error || {message: 'Server Error'}));
}
login(form): Observable<Response> {
const headersObj = new Headers();
headersObj.set('Content-Type', 'application/json');
const requestArg: RequestOptionsArgs = { headers: headersObj, method: 'POST' };
// const telephone = form.telephone;
// const password = form.password;
return this.http.post(`${this.baseUrl}/login`, form, requestArg)
.map((response: Response) => {
const user = response.json();
if (user.response.status) {
localStorage.setItem('loggedUser', JSON.stringify(user.response));
}
return user.response;
})
.catch((error: any) => Observable.throw(error.json().error || {message: 'Server Error'}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('loggedUser');
}
}
My Route Guard:
import { Injectable } from '#angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
// import {AuthenticateService} from './authenticate.service';
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if ((!localStorage.getItem('loggedUser'))) {
// not logged in so redirect to login page
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
} else {
return true;
}
}
}
App routing Module:
import { NgModule } from '#angular/core';
import {RouterModule, Routes} from '#angular/router';
import {LoginComponent} from './login/login.component';
import {RegisterComponent} from './register/register.component';
export const routes: Routes = [
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
];
#NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
Guarded Module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import {FormsModule} from '#angular/forms';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { DashboardComponent } from './dashboard.component';
import { DashboardHomeComponent } from './dashboard-home/dashboard-home.component';
import { UsersComponent } from './users/users.component';
import { TransactionsComponent } from './transactions/transactions.component';
import { UsersService } from './services/users.service';
#NgModule({
imports: [
CommonModule,
FormsModule,
RouterModule,
DashboardRoutingModule
],
exports: [ DashboardComponent ],
declarations: [ DashboardComponent, DashboardHomeComponent, UsersComponent, TransactionsComponent],
providers: [ UsersService ]
})
export class DashboardModule { }
Feature Module Component:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import {DashboardComponent} from './dashboard.component';
import {DashboardHomeComponent} from './dashboard-home/dashboard-home.component';
import {UsersComponent} from './users/users.component';
import {TransactionsComponent} from './transactions/transactions.component';
import {AuthGuard} from '../auth.guard';
export const dashboardRoutes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [ AuthGuard ],
children: [
{path: '', component: DashboardHomeComponent},
{path: 'users', component: UsersComponent},
{path: 'transactions', component: TransactionsComponent}
]}
// {path: 'dashboard', component: DashboardComponent}
];
#NgModule({
imports: [
RouterModule.forChild(dashboardRoutes)
],
exports: [
RouterModule
],
declarations: []
})
export class DashboardRoutingModule { }
I found the error, I imported Router module in my feature module and also in my feature-routing module.

I am trying to build angular 4 application which is new to me. After I pushed into nginx server getting some Issue

The problem is when directly redirecting to
http://localhost:4200/about working fine but after pushing into
nginx server, when I try to redirect to www.webpage.com/about
getting error(nginx 404 error).
But its working fine when you redirect to www.webpage.com and then click on about.
Getting error only I am trying to open direct url as www.webpage.com/about or www.webpage.com/contact or
www.webpage.com/blog
import { NgModule } from '#angular/core';
import { HttpModule } from '#angular/http';
import { RouterModule } from "#angular/router";
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { appRoutes } from "./app-routing.module";
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { BlogComponent } from './blog/blog.component';
import { ClientsComponent } from './clients/clients.component';
import { ContactComponent } from './contact/contact.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
BlogComponent,
ClientsComponent,
ContactComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forRoot(appRoutes)
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule {
}
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { ClientsComponent } from './clients/clients.component';
import { ContactComponent } from './contact/contact.component';
import { BlogComponent } from './blog/blog.component';
export const appRoutes: Routes = [
{ path: '', redirectTo: '/', pathMatch: 'full' },
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'clients', component: ClientsComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'page-not-found', component: PageNotFoundComponent },
{ path: '**', component: HomeComponent }
];
#NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {
}
You will need to configure your web server to redirect all unknown (404) requests to index.html, which will allow the Angular application to then route your user to the desired route/view.
You can try something like this :
error_page 404 =200 /index.html;
Source : How do I force redirect all 404's (or every page, whether invalid or not) to the homepage?
try_files $uri $uri/ /index.html;
This line has to be added in the nginx.conf incase of Windows server or in /etc/nginx/sites-enabled/default in case of ubuntu server.
That piece of code will look for angular paths before throwing a 404 error.
angular deployment check this out

Categories