Angular2中的路由

时间:2016-01-29 15:34:54

标签: angular angular2-routing

我正在学习角度2,但面临着一个让我感到困惑的问题。如果我有corenav组件,并且我希望nav组件呈现core组件中定义的路由,我该怎么做?

因为现在我已经在core组件中定义了路由,并在[routerLink]="['About']"组件模板中添加了nav属性,但似乎它可以'找到它或发生了一些错误,因为只要我添加这个属性指令就会导致核心组件无法加载以及半冻结浏览器,就像它执行某种无限循环一样。

我没有错误告诉我任何对我有帮助的事情。我已经在angular2中阅读了有关路由的文档,但它们只用一个组件显示它,而不是在尝试从单独的组件加载core组件中定义的路由时。这可能是什么问题?

core.component.ts

import {Component} from 'angular2/core';
import {RouteConfig} from 'angular2/router';
import {NavComponent} from '../nav/nav.component';
import {AboutComponent} from '../about/about.component';
import {ContactComponent} from '../contact/contact.component';

@Component({
  selector: 'core-app',
  templateUrl: './app/assets/scripts/modules/core/core.component.html',
  styleUrls: ['./app/assets/scripts/modules/core/core.component.css'],
  directives: [NavComponent]
})

@RouteConfig([
  {path: '...', name: 'Home', component: CoreComponent},
  {path: '/about', name: 'About', component: AboutComponent},
  {path: '/contact', name: 'Contact', component: ContactComponent}
])

export class CoreComponent {

}

nav.component.ts

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {NavService} from '../nav/nav-api.service';
import {NAVLIST} from '../nav/nav-list';

@Component({
  selector: 'nav-list',
  templateUrl: './app/assets/scripts/modules/nav/nav.component.html',
  styleUrls: ['./app/assets/scripts/modules/nav/nav.component.css'],
  providers: [NavService],
  directives: [ROUTER_DIRECTIVES],
  host: {
    '(mouseenter)': 'show()',
    '(mouseleave)': 'hide()'
  }
})

export class NavComponent {
  public isToggled = false;
  public links = NAVLIST;

  constructor(private _navService: NavService) {}

  show() {
    this.isToggled = this._navService.show();
  }

  hide() {
    this.isToggled = this._navService.hide();
  }
}

nav.component.html

<nav class="nav-wrapper" [class.is-toggled]="isToggled" [class.is-hidden]="!isToggled">
  <ul class="nav-links">
    <li class="nav-link" *ngFor="#link of links">
      <a [routerLink]="['About']">
        <div class="label-wrapper">{{link.label}}</div>
        <div class="icon-wrapper"><i class="{{link.icon}}"></i></div>
      </a>
    </li>
  </ul>
</nav>

1 个答案:

答案 0 :(得分:3)

看看这个:{path: '...', name: 'Home', component: CoreComponent},

通过执行'...',您说其他组件将解决路径(该组件需要RouteConfig),您希望CoreComponent处理所有路由,但所有路由都已通过它。所以你无限期地重定向到它。