I am going to develop a simple Angular 2 application. I have created a project with routing, using Angular CLI and added several components to the app using \'ng generate co
I used lite-server.
npm i -D lite-server
then in my package.json file:
"scripts": {
"ci:serve:employee-onboarding": "ng build --prod --project=employee-onboarding && lite-server -c lite-server-config.json"
}
to run it: npm run ci:serve:employee-onboarding
my lite-server-config.json file looks like this
{
"port": 4201,
"server": { "baseDir": "dist/apps/employee-onboarding" }
}
As per the documentation at https://angular.io/guide/deployment (Apache, you could also look for nginx) You need to point the server to index.html using the .htaccess file as
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
It will be solved in this way:
Case-1: For version less than Angular 5.1
1) Use HashLocationStrategy like mentioned below: In AppModule do the following.
1.1) import { HashLocationStrategy, LocationStrategy } from '@angular/common';
1.2) providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
Case-2: For version equal or more than Angular 5.1
2.1) Angular has introduced this property onSameUrlNavigation for overcoming refresh issue on the server.
2.2) Add onSameUrlNavigation to the RouterModule.forRoot
in imports array .
a) In Application main routing module, i,e app.routing.module.ts / app.routing.ts add the property
See below:
@ngModule({
imports:
[
RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})
],
exports: [RouterModule],
});
Hope it help somebody.
Change your index.html
<base href="/">
to
<base href="./">
Because we are using Tomcat we have mentioned this(.) for Routing is based on this(/) So same like http-server
I mean running normally ng serve you have seen only
http://localhost:4200/
but run in server you have put your build into(dist) in webapps
so its come like
http://localhost:8080/dist/
so you need to add <base href="./">
i think this is the problem for you may be solved.
If you, like me, want to make no code changes at all, simply use this instead:
https://www.npmjs.com/package/angular-http-server
For Apache server:
in the Production servers
Add or create ".htaccess" file into the project root, add a rewrite rule to the .htaccess file as shown
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html