my app.module.ts
@NgModule({
.......
providers: [
....
{ provide: LocationStrategy, useClass: HashLocationStrategy},
....
]
});
when i remove this part, it's works in my localhost but after taking a ng build or ng build --prod , when i refresh the page or h5 it doesn't work. It gives 404 error. I want to remove hash(#) from my url. Any solution ?
You can check the angular guide about deployment
Let's talk about the difference between HashLocationStrategy
and PathLocationStrategy
. For more info, check the docs
Angular, by default, uses PathLocationStrategy
.
Let's say you have following routes in your application.
const routes: Route[] = [{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent
}];
When you route to this component, your address bar will look like localhost:4200/home
. If you used HashLocationStrategy
, it would look like localhost:4200/#home
. So, what's the difference here?
PathLocationStrategy
When you are on page Home
and hit F5
button or refresh the page, the browser will make a request to localhost:4200/home
which will handled by angular-cli and you'll have your HomeComponent
returned.
HashLocationStrategy
Likewise, when you hit F5
, the browser will make the request to localhost:4200
this time, because it ignores whatever comes after #
If you don't want to have #
, then remove the part you pointed out. It'll be PathLocationStrategy
by default. However, this brings us to part when you run your application outside of angular-cli
which means building and serving it from some server. Let's say you build your application with ng build
and you have your minified, compiled javascript files. You deploy it to some server which runs on yourdomain.com
Also, you put this built, bundled angular application at some url so that people will access your application from yourdomain.com/ng-app
, everything is fine here. Even, when you route to HomeComponent
, it'll work and your address bar will look like yourdomain.com/ng-app/home
. However, when you hit F5
at this point, your browser will make request to yourdomain.com/ng-app/home
which does not exist on your server because you serve your application from /ng-app
. You have to do some config at your server side so that you can serve everything that starts with /ng-app/**
.
For example, my spring application has this method that returns the angular application,
@GetMapping("/ng-app/**")
So when my server gets a request that starts with /ng-app
, it just passes this to angular application which will handle the correct route.
Hope, this clarifies it for you.