2017-02-02 41 views
0

我实现了路由到我的应用程序,但它不按预期工作。当我点击Login按钮时,它应该导航到一个新的登录页面,但是它会在主页面内创建一个登录页面(VehicleComponent)。下面的代码:Angular2路由器“覆盖”模板

APP-routing.module.ts

import { NgModule } from '@angular/core'; 
import { RouterModule, Routes } from '@angular/router'; 

import { VehicleComponent } from './vehicle.component'; 
import { LoginComponent } from './login.component'; 

const routes: Routes = [ 
    //{ path: '', redirectTo: '/vehicle', pathMatch: 'full' }, 
    { path: 'vehicle', component: VehicleComponent }, 
    { path: 'login', component: LoginComponent } 
]; 

@NgModule({ 
    imports: [RouterModule.forRoot(routes)], 
    exports: [RouterModule] 
}) 
export class AppRoutingModule { } 

VehicleComponent.ts

toLogin(): void { 
    console.log("toLogin button"); 
    this.router.navigate(['login']); 
    } 

模板

<router-outlet></router-outlet> 
<button class="btn btn-default" type="button" (click)="toLogin()">Login</button> 
部分

LoginComponent

onSubmit(): void { 
    console.log("Submit button"); 
} 
goBack(): void { 
    console.log("Back button"); 
    this.location.back(); 
} 

VehicleComponent

After clicking Login 按钮 “后退” 上LoginComponent工作正常,在VehicleComponent只是 “登录” 被打破了。任何想法如何解决这个问题?

+2

'this.router.navigate(['/ login']);' – anshuVersatile

+0

我试过了,但它也不起作用。 – Haseoh

+0

如果您通过直接输入网址访问http:// yoursite/login,您会看到什么? ' – AngularChef

回答

0

我设法解决了这个问题。我添加了另一个组件,只是作为<router-link></router-link>的占位符,然后在我的app-routing.module中取消注释{ path: '', redirectTo: '/vehicle', pathMatch: 'full' }。现在它按预期工作。