路由URL的默认值在角度4中错误

时间:2018-10-19 04:24:44

标签: angular angular4-router

我正在学习角度4,我正在尝试创建一个应用程序,该应用程序的着陆/主页将显示“欢迎”消息。它将有两个选项卡“ home and products”,然后单击“ product”选项卡将显示产品列表

我已经实现了它,我面临的唯一一个问题是默认URL始终采用productlist,并且刷新后会在首页上显示产品列表。

default productList

app.module.ts文件

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {RouterModule , Routes} from '@angular/router';
import { AppComponent } from './app.component';
import { productListComp } from './product.list';
import { homeComp } from './home.comp';
const routes : Routes=[
{path:"",redirectTo:"/home",pathMatch:"full"},
{path:"home",component:homeComp},
{path:"productList",component:productListComp}
];
@NgModule({
declarations: [
AppComponent,
productListComp,
homeComp
],
imports: [
BrowserModule,
RouterModule.forRoot(routes)
],
providers: [
  ],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:

import { Component } from '@angular/core';
import {Router} from '@angular/router'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _router : Router)
{
}
productListSel(){
console.log("in productListSel");
this._router.navigate(['productList']);
}

homeSel(){
console.log("in homeSel");
this._router.navigate(['home']);
}
} 

app.component.html

<ul class="nav nav-tabs">
   <li class="nav-item"> <a class="nav-link active" data-toggle="tab" 
   (click)="homeSel()">home</a>    </li>
   <li class="nav-item"> <a class="nav-link" data-toggle="tab" 
   (click)="productListSel()">products</a>    </li>

</ul>

如果单击主页选项卡,则显示正确的“ Welcome”消息,但是如果我只是执行“ ng serve -o”或刷新页面,则总是productList显示。 我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您需要更新您的路线,例如;

   const routes : Routes=[
    {path:"",redirectTo:"/home",pathMatch:"full"},**strong text**
    {path:"home",component:homeComp},
    {path:"productList",component:productListComp},
    {path: '**', component: homeComp }  ==> Added
];