0

In developer section (localhost:4200) is working fine. After completing the build application loading and working fine but url when i type and press enter it is not working.

my router:

export const appRoutes : Routes = [
    { path: '', redirectTo: 'material', pathMatch: 'full' },
    {path:'material',component: MaterialComponent},
];

and my module.ts file

imports: [            
    RouterModule.forRoot(appRoutes,{ enableTracing: true }),BrowserModule,FormsModule,HttpModule,MaterialModule,BrowserAnimationsModule,RouterModule    
  ],

Error:

enter image description here

Why giving custom url is not working after build?

eko
  • 39,722
  • 10
  • 72
  • 98
Siva Unique
  • 189
  • 2
  • 17

2 Answers2

0

The problem is Angular takes care of the url after the dns (localhost:4200) part. So when you type localhost:4200/someurl, The network will query your backend for that full url, and if it doesn't exists you will get a 404. You have 2 options here:

1) Use HashLocation Strategy which I don't recommend because it breaks AoT.

2) Define a redirection function in your back-end code. For nodejs we do it like this:

app.get('/*',  function(req, res, next) {
    res.sendFile('index.html', { root: __dirname + '/dist' });
});

Related topic: Angular 2.0 router not working on reloading the browser

eko
  • 39,722
  • 10
  • 72
  • 98
  • @echonax-just now I have included hashlocation it's working fine form me. But i don't now how to apply redirection using angular 2, can you help me to resolve this one. Back end i am using php – Siva Unique Aug 05 '17 at 08:18
  • @SivaUnique It's not related with angular as we've discussed :-) unfortunately I don't know php :( – eko Aug 05 '17 at 08:19
  • Yes Echonax, can you tell me the logic how we will do this one(i will build logic in php) – Siva Unique Aug 05 '17 at 08:31
  • @SivaUnique I've added php tag to your question, hopefully someone who knows php would answer it. – eko Aug 05 '17 at 08:42
0

I have solved using Hash. We need to import below modules in module.ts

import { HashLocationStrategy, LocationStrategy } from '@angular/common';

and we need to include providers as given below in module.ts file.

  providers: [AppCommonService,{provide: LocationStrategy, useClass: HashLocationStrategy}],
Siva Unique
  • 189
  • 2
  • 17
  • If you use hashlocation strategy, you won't be able to use ahead of time compilation. – eko Aug 10 '17 at 12:36