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

标签 angular angular2-routing

在 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. “null 的属性‘map’”指的是什么?
  2. 有什么方法可以不通过 ngOnInit() 来创建默认路由吗?
  3. 或者如何在页面重新加载期间解决此 URL 和页面内容不一致的问题?

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

有关我的文件夹结构和路由设置的更多信息,请参阅 Angular2 RC1 child routes defined but not recognized

更新: 如果我使用

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

配对

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

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

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

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

  1. 在 app.component.ts 的@Routes 中使用 '/' 或 '*' 定义根路径

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

  2. 去掉 app.component.ts 中的 ngOnInit(),这样它就不会更改 URL。

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

最佳答案

在 RC1 中对我有用的是

{ 路径:'',组件:FooComponent,索引:真} { 路径:'foo',组件:FooComponent }

关于刷新页面时angular2 rc1默认路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37151628/

相关文章:

angular - Angular 2 中的延迟加载文件夹

angular - 如何检测在 ngFor 之后 DOM 何时准备好?

Angular TypeError : _angular_core__WEBPACK_IMPORTED_MODULE_1__. ɵɵdefineInjectable 不是函数

google-maps - 带有 angular2 应用程序的 angular2-google-maps

html - Angular Dom Sanitizer HTML 无法复制文本

Angular 2 新路由器 : How to get router parameters of a child component?

angular - Ionic2/Angular2 - 读取自定义配置文件

可选参数的 Angular RouterLink queryParamsHandling

angular - 在 Azure 中使用路由托管 Angular2 应用程序

javascript - Angular2 组件不检测路由参数更新(路由器 3.0)