刷新页面时angular2 rc1默认路由问题

angular2 rc1 default route issue when refresh page

在 RC1 的新路由器中,无法再使用 useAsDefault。相反,默认路由现在通过

在 app.component.ts 中实现
  ngOnInit() {
    this.router.navigate(['/login']);
  }

如果我通过按浏览器上的 Reload 按钮刷新我的页面,那么我当前的页面 url,例如 http://localhost:3000/heroshell/heroes 将被更改到 http://localhost:3000/login 因为每次我点击重新加载按钮时它都会经过 app.component.ts

  ngOnInit() {
    this.router.navigate(['/login']);
  }

我的当前页面仍会显示,但会出现错误。

browser_adapter.ts:78 EXCEPTION: Error in app/apps/hero/hero-shell.component.html:3:7
browser_adapter.ts:78 ORIGINAL EXCEPTION: TypeError: Cannot read property 'map' of null

这里是app/apps/hero/hero-shell.component.html

<my-app1>
<h1>{{title}}</h1>
<nav>
    <a [routerLink]="['dashboard']">Dashboard</a>
    <a [routerLink]="['heroes']">Heroes</a>
</nav>
<router-outlet></router-outlet>
</my-app1>

所以我的问题是

  1. "property 'map' of null"指的是什么?
  2. 有什么方法可以不通过 ngOnInit() 来创建默认路由吗?
  3. 或者如何解决这个URL和页面重新加载时页面内容不一致的问题?

Beta 路由没有这样的行为,因为不需要通过 ngOnInit() 来定义默认路由。

有关我的文件夹结构和路由设置的更多信息,请参阅

更新: 如果我使用

  { path: '/', component: Login }, 

配对

  ngOnInit() {
    this.router.navigate(['/']);
  }

然后当点击重新加载按钮时,URL 将更改为 http://localhost:3000/,并且错误保持不变。

同样,如果我通过上述更新将路径更改为“”,那么当点击重新加载按钮时,URL 将更改为“http://localhost:3000/[=70” =]' 并且错误保持不变。

解决问题的关键是结合使用两件事:

  1. 在app.component.ts

    中的@Routes中使用'/'或'*'定义根路径

    { 路径:'*',组件:登录},

  2. 去掉app.component.ts中的ngOnInit()这样就不会改变URL.

再次感谢大家的意见。干杯:)

使用新 RC 路由器定义默认路由的一种方法是

@Routes([
    { path: '/',  component: Login }
])

抱歉,第 1 和第 3 个问题没看懂,为此:

  1. Is there any way to make a default route without going through ngOnInit()?

你试过'*'作为默认路由吗?

{ path: '/heroshell', component: HeroShellComponent },
{ path: '/home',  component: HomeComponent },
{ path: '/login', component: Login }, 
{ path: '*', component: Login }, 

默认路由将是 'Login',“/login”路径也可以。

@Routes([

   { path: '/', component: HomeComponent },

   { path: '/about', component: AboutComponent }
])

在这两个组件中,Home 组件将成为默认组件。

更新到 RC5

With RC5 you cannot have '/' in your path. Instead use ' ' or use '*'

在 RC1 中对我有用的是

{ path: '', component: FooComponent, index: true } { path: 'foo', component: FooComponent }

@NgModule({
    imports: [
        RouterModule.forRoot([
            { path: 'login', component: LoginComponent },
            { path: '', component: LoginComponent },/*default*/
            { path: '**', component: PageNotFoundComponent }/*matches all*/
        ])
    ],
    exports: [
        RouterModule
    ]
})

第二条路由中的空路径匹配为每一级路由的默认路径。它还允许在不扩展 URL 路径的情况下添加路由。

最后一条路由中的**表示我们路由的通配符路径。如果请求的 URL 与我们配置中定义的路由的任何路径都不匹配,路由器将匹配此路由。这对于显示 404 页面或重定向到另一个路由很有用。

配置中路由的顺序很重要,这是设计使然。路由器在匹配路由时采用先匹配优胜策略,因此更具体的路由应该放在不太具体的路由之上。 https://angular.io/docs/ts/latest/guide/router.html