'router-outlet'在主模板上没有'routerLink'时无法正常工作

And*_*res 5 angular2-routing angular-cli angular

我刚刚使用Angular CLI创建了一个新的角度项目,并使用以下命令在其中搭建了一个新的路由用户.

ng new myproj
cd myproj 
ng g route user
Run Code Online (Sandbox Code Playgroud)

然后我使用了Angular CLI服务器ng serve.

但是当我访问页面时,我无法看到登录模板的内容,/login除非我添加了某个路径的链接,即:

<a [routerLink]="['/user']">User Info</a>
Run Code Online (Sandbox Code Playgroud)

当我添加上面的行,然后router-outlet填充,但如果我删除此行,则router-outlet再次呈现为空.

这里发生了什么事?

有人知道为什么会这样吗?

示例文件

/src/app/myproj.component.ts

import { Component } from '@angular/core';
import { Routes, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'myproj-app',
  templateUrl: 'myproj.component.html',
  styleUrls: ['myproj.component.css'],
  directives: [ROUTER_DIRECTIVES],
  providers: [ROUTER_PROVIDERS]
})
@Routes([
  {path: '/user', component: UserComponent}
])
export class MyprojAppComponent {
  title = 'Main Component working!';
}
Run Code Online (Sandbox Code Playgroud)

/src/app/myproj.component.html

<h1>{{title}}</h1>
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

而不可理解的解决方法

<a [routerLink]="['/user']">User Info</a>
Run Code Online (Sandbox Code Playgroud)

/src/app/+user/user.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-user',
  templateUrl: 'user.component.html',
  styleUrls: ['user.component.css']
})
export class UserComponent implements OnInit {

  constructor() {}

  ngOnInit() {
  }

}
Run Code Online (Sandbox Code Playgroud)

/src/app/+user/user.component.html

<p>
  It should be showing but it isn't!
</p>
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 6

这是新RC路由器中的一个已知问题.

或者你也可以

export class MyprojAppComponent {
  constructor(router:Router) {}
Run Code Online (Sandbox Code Playgroud)

要调用路由器,必须使用其中一种解决方法.