Angular - Unhandled Navigation Error after building

前提是你 提交于 2021-02-18 22:08:47

问题


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:

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


回答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.




回答2:


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

<base href="#">



回答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.




回答4:


app/module.ts:

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


@NgModule({
 ...
 ],
 providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})


来源:https://stackoverflow.com/questions/53833316/angular-unhandled-navigation-error-after-building

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!