主路由器:
@RouteConfig([
{ path: '/', name: 'Intro', component: IntroComponent, useAsDefault: true },
{ path: '/locator/...', name: 'Locator', component: LocatorComponent },
])
子路由器:
@RouteConfig([
{ path: '/bydistrict', name: 'ByDistrict', component: ByDistrictComponent },
{ path: '/bycounty', name: 'ByCounty', component: ByCountyComponent },
{ path: '/byregion', name: 'ByRegion', component: ByRegionComponent, useAsDefault: true }
主要导航:
<a class="nav-item nav-link" href="#" [routerLink]="['Locator', 'ByDistrict']">Search</a>
<a class="nav-item nav-link" href="#" [routerLink]="['Locator', 'ByCounty']">Counties</a>
<a class="nav-item nav-link" href="#" [routerLink]="['Locator', 'ByRegion']">Regions</a>
问题#1:单击主导航链接时, View 始终会正确更新,但 URL 永远不会更新以反射(reflect)选择的第一个导航项“搜索”。它始终保持设置为先前的事件路径。另外两个更新正确。
问题#2:从子组件(例如 ByDistrictComponent)导航到新路线时,URL 会更新以反射(reflect)新路线,但 View 不会更新。无论是否使用 [routerLink]="['/Locator', 'ByCounty']
都会出现此问题使用或来自代码 this._router.navigate(...)
.
对于这两种情况,控制台中都不会报告错误。
我今天刚刚更新到当前版本的 Angular 2 (2.0.0-beta.11) 及其依赖项。我使用的之前版本(beta.9)中也存在该问题。
我将这两个问题作为一个问题发布,因为我认为它们可能都与使用子路由器时的意外行为有关。
更新#1
只有当 Router 被注入(inject)到通过 ByDistrictComponent(在子路由中引用)的指令加载的组件的构造函数中时,这两个问题才会开始发生。
import { Component, OnInit } from 'angular2/core';
import { ROUTER_DIRECTIVES, ROUTER_PROVIDERS, Router } from 'angular2/router';
@Component({
...
})
export class DistrictListComponent implements OnInit {
constructor(
private _router: Router) { // <-- causes both issues
}
...
}
最佳答案
注意:
1) 我更改了 index.html
页面。
2)更改了main.ts
main.ts
import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {Router,ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router';
import {App} from './app';
bootstrap(App, [
ROUTER_PROVIDERS,bind(APP_BASE_HREF).toValue(location.pathname)
//provide(LocationStrategy,{useClass: HashLocationStrategy} you can also use this if you don't want to you bind().
])
.catch(err => console.error(err));
关于Angular 2嵌套路由: view or url not being updated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110370/