我的主页组件html
<nav class="navbar navbar-default">
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li [class.active]="makeActive('home')"><a routerLink="home">Users</a></li>
<li [class.active]="makeActive('posts')"><a routerLink="posts">Posts</a></li>
</ul>
</nav>
<div class="container">
<router-outlet></router-outlet>
</div>
我的homecomponent.ts
import {Component} from '@angular/core';
import {UsersService} from './users.service';
import {Observable} from 'rxjs/Rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit, OnDestroy} from '@angular/core'
@Component({
selector : 'home',
template : `<h1>Home</h1>
<p><a class="btn btn-primary" routerLink="Newuser">Add User</a></p>
`,
providers : [UsersService, HTTP_PROVIDERS]
})
export class HomeComponent implements OnInit{
usersList: any[];
constructor(private _usersService: UsersService){}
ngOnInit(){
this._usersService.getUsers()
.subscribe(users => this.usersList = users);
}
}
当我第一次点击AddUser按钮时,页面url变为localhost:3000 / Newuser并且页面呈现正确,然后单击home后将呈现主视图。 然后,如果我再次单击adduser,则url将变为localhost:3000 / home / Newuser,并且不会加载新用户视图。
这是我的路由器文件
import {Router, RouterModule} from '@angular/router';
import {HomeComponent} from './home.component';
import {PostsComponent} from './posts.component';
import {UserAdditionComponent} from './user-addition.component'
export const routing = RouterModule.forRoot([
{path: '', component: HomeComponent},
{path: 'posts', component: PostsComponent},
{path: 'Newuser', component: UserAdditionComponent},
{path: '**', component: HomeComponent}
])
答案 0 :(得分:1)
这是因为routerLink
采用相对路径。
如果您转到/home
,则会Newuser
追加/home/...
要解决此问题,您必须在'/'
之前添加Newuser
:
<p><a class="btn btn-primary" routerLink="/Newuser">Add User</a></p>