angular – ‘router-outlet’在主模板上没有’routerLink’时无法正常工作

前端之家收集整理的这篇文章主要介绍了angular – ‘router-outlet’在主模板上没有’routerLink’时无法正常工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚使用Angular CLI创建了一个新的角度项目,并使用以下命令在其中搭建了一个新的路由用户.

ng new myproj
cd myproj 
ng g route user

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

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

<a [routerLink]="['/user']">User Info</a>

当我添加上面的行时,路由器插座就会被填满,但是如果我去掉这一行,那么路由器插座再次呈现为空.

这里发生了什么事?

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

示例文件

/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!';
}

/src/app/myproj.component.html

<h1>{{title}}</h1>
<router-outlet></router-outlet>

而不可理解的解决方法

<a [routerLink]="['/user']">User Info</a>

/ 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() {
  }

}

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

<p>
  It should be showing but it isn't!
</p>

解决方法

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

或者你也可以

export class MyprojAppComponent {
  constructor(router:Router) {}

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

猜你在找的Angularjs相关文章