Angular - Unhandled Navigation Error after building

10,156

Solution 1

Using Angular routing engine will force you to host your app in some server (e.g. IIS, NodeJS etc.)

A simple angular app without routes can run without hosting it on a server.

From Angular docs:

Angular apps are perfect candidates for serving with a simple static HTML server. You don't need a server-side engine to dynamically compose application pages because Angular does that on the client-side.

If the app uses the Angular router, you must configure the server to return the application's host page (index.html) when asked for a file that it does not have.

Solution 2

Angular routing works if you use hash routing and define your base href as follows in your index.html.

<base href="#">

Solution 3

In my case I would get:

Unhandled Navigation Error: main.af3eff424835a3d5642f.js:1

Because my base url was set to https://

<base href="https://example.com" />

But I was loading the site over http://

http://example.com

Solution was to either use the https:// url OR change the base url to allow access via http.

Solution 4

app/module.ts:

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


@NgModule({
 ...
 ],
 providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
Share:
10,156
Elkin
Author by

Elkin

Updated on June 15, 2022

Comments

  • Elkin
    Elkin almost 2 years

    I have built a simple angular app with 2 routes through the following command:

    ng build --aot --prod --base-href ./
    

    Then i open the index.html file located in the dist folder and the app runs but the the routes don't work and i get the following warning on console:

    enter image description here

    Hope to have explained my question well. Thanks in advance.

  • Elkin
    Elkin over 5 years
    Why? Could it be because of the routing system?
  • benshabatnoam
    benshabatnoam over 5 years
    I think you are correct, this is because of the routing system. Check out this link
  • jackofallcode
    jackofallcode over 4 years
    This worked for me, I had already setup Angular routing at the beginning and didn't really want to revert anything.
  • Sheed
    Sheed over 3 years
    my school server hosting wouldn't work, this works great as a standalone !
  • Jeremy Caney
    Jeremy Caney about 3 years
    Thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts.
  • Stewii
    Stewii about 3 years
    This seems like the best answer, and a most common use case.