【发布时间】:2016-06-03 13:59:21
【问题描述】:
我已经编写了我的第一个 Angular Dart 应用程序,但是路由出了点问题......
@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 {}
仪表板页面:
@Component(
selector: 'dashboard-page',
template: '<strong>This is the Dashboard Page</strong>')
class DashboardPage {}
main.dart:
// bootstrap angular2
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(APP_BASE_HREF, useValue: '/'),
provide(LocationStrategy, useClass: HashLocationStrategy)
]);
当我的应用程序启动时,它按预期转到http://localhost:8080/dashboard,当单击Home 链接时,它正确转到http://localhost:8080/home。如果我现在刷新页面,我会收到错误 404
然后我将引导部分更改为:
// bootstrap angular2
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(APP_BASE_HREF, useValue: '/#/'),
provide(LocationStrategy, useClass: HashLocationStrategy)
]);
网址现在如下(我更喜欢这种风格,因为旧版应用程序使用相同的网址格式)
http://localhost:8080/#/dashboard
http://localhost:8080/#/home
如果我点击刷新,不再收到错误 404,但页面会重定向回 http://localhost:8080/#/dashboard 页面。
我正在使用 pub serve 运行应用程序
有什么方法可以将 onHashChange 事件绑定到 Angular 路由器,这样如果我刷新 http://localhost:8080/#/home 它实际上会路由到 HomeComponent?
【问题讨论】:
-
AFAIR URL 格式与
HashLocationStrategy一样。当您完全删除provide(APP_BASE_HREF, ...)行时会发生什么(不确定HashLocationStrategy是否需要它)。您能否也尝试将<base href="/">(而不是provide(APP_BASE_HREF, ...))作为head 标签中的第一个元素?