Angular2路由在重新加载页面时给出404 [英] Angular2 Routing gives 404 when reloading page
问题描述
我写了我的第一个Angular Dart应用程序,但是路由是错误的...
I've written my first Angular Dart app, but something is wrong wit the routing ...
@Component(
selector: 'ahpmui',
template: '''
<strong>My First Angular 2 App - {{name}}</strong>
<br />
<router-outlet>
</router-outlet>
<br />
<nav>
<a [routerLink]="['HomePage']">Home</a> |
<a [routerLink]="['DashboardPage']">Dashboard</a>
</nav>
''',
directives: const [ROUTER_DIRECTIVES],
providers: const [
ROUTER_PROVIDERS,
HomePage,
DashboardPage
]
)
@RouteConfig(const [
const Route(path: '/dashboard', component: DashboardPage, name: 'DashboardPage', useAsDefault: true),
const Route(path: '/home', component: HomePage, name: 'HomePage')
])
class AppComponent {
String name = "Sample App";
}
首页:
@Component(
selector: 'home-page',
template: '<strong>This is the Home Page</strong>')
class HomePage {}
DashboardPage:
DashboardPage:
@Component(
selector: 'dashboard-page',
template: '<strong>This is the Dashboard Page</strong>')
class DashboardPage {}
main.dart:
main.dart:
// bootstrap angular2
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(APP_BASE_HREF, useValue: '/'),
provide(LocationStrategy, useClass: HashLocationStrategy)
]);
当我的应用程序启动时,它会转到 http:// localhost: 8080 / dashboard
按预期,当点击首页
链接时,它会正确到 http:// localhost:8080 / home
。如果我现在刷新页面,我会收到一条错误 404
When my app starts up, it goes to http://localhost:8080/dashboard
as expected, when clicking on the Home
link, it correctly goes to http://localhost:8080/home
. If I now refresh the page, I get an error 404
然后将引导部分更改为:
I then change the bootstrap part to this:
// bootstrap angular2
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(APP_BASE_HREF, useValue: '/#/'),
provide(LocationStrategy, useClass: HashLocationStrategy)
]);
现在的URL如下(我喜欢这种风格,因为遗留应用程序使用的是同一个网址格式)
URLs are now as follow (I prefer it in this style since the legacy app is using this same url format)
http://localhost:8080/#/dashboard
http://localhost:8080/#/home
如果我点击刷新,不再收到错误404,但是页面重定向回 http:// localhost:8080 /#/ dashboard
页面。
If I hit refresh, no longer get the error 404, but the page redirects back to the http://localhost:8080/#/dashboard
page.
c $ c> pub服务
I'm running the app using pub serve
有什么办法可以绑定 onHashChange
event into the Angular Router,如果我刷新 http:// localhost:8080 /#/ home
它实际上路由到HomeComponent?
Is there any way I can tie in the onHashChange
event into the Angular Router so that if I refresh http://localhost:8080/#/home
that it actually routes to the HomeComponent ?
推荐答案
从 AppComponent
中移除 ROUTER_PROVIDERS,你已经在
bootstrap()
中。 ROUTER_PROVIDERS
只应提供一次。
Remove ROUTER_PROVIDERS,
from AppComponent
, you have them in bootstrap()
already. ROUTER_PROVIDERS
should be provided only once.
这篇关于Angular2路由在重新加载页面时给出404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!