Angular 6 路由重定向未正确重定向

当我转到 localhost:4200 时,我希望被定向到AboutComponent(在/home路径上),并且还希望/home被附加到 URL,但是我被重定向到PageNotFoundComponent,并且/home没有被附加到网址。任何想法我做错了什么?谢谢!


app-routing.module.ts


import { NgModule } from '@angular/core';

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

import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

import { AppComponent } from './app.component';

import { AboutComponent } from './about/about.component';

import { SignupComponent } from '../signup/signup.component';


const routes: Routes = [

 {path: 'signup', component: SignupComponent },

  {path: '' , redirectTo: '/home', pathMatch: 'full'},

  {path: '**', component: PageNotFoundComponent}


];


@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }


app.module.ts


import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';


import { Router } from '@angular/router';


import { AppComponent } from './app.component';

import { PageNotFoundComponent } from './page-not-found/page-not-found.component';


import { AdminModule } from './admin/admin.module';

import { AppRoutingModule } from './app-routing.module';

import { AboutModule } from './about/about.module';


@NgModule({

  imports: [

    BrowserModule,

    FormsModule,

    AboutModule,

    AppRoutingModule

  ],

    declarations: [

    AppComponent,

    PageNotFoundComponent

  ],


  providers: [CookieService],

  bootstrap: [AppComponent]

})

export class AppModule { 

  constructor(router: Router) {


  }

}


about-routing.module.ts


import { NgModule } from '@angular/core';

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

import { AboutComponent } from './about.component';

import { PageNotFoundComponent } from '../page-not-found/page-not-found.component';


const aboutRoutes: Routes = [

  {path: 'home', component: AboutComponent}

  {path: '**', component: PageNotFoundComponent}

];


@NgModule({

  imports: [RouterModule.forChild(aboutRoutes)],

  exports: [RouterModule]

})

精慕HU
浏览 307回答 2
2回答

呼唤远方

App-routing 模块是父级,而 about-routing 模块是子级,所以当你被 '/home' 触发时,你需要告诉父级加载子路由,就像const routes: Routes = [ {path: 'signup', component: SignupComponent }, {path: '' , redirectTo: '/home', pathMatch: 'full'}, {  path: 'home',  loadChildren: './About/about.module.ts#AboutModule' }, {path: '**', component: PageNotFoundComponent}];当我们在路由中提供 'loadChildren' 时,父模块将加载子模块(关于模块),并调用路由 forchild,然后将工作。为什么它失败了,因为在父级中没有提到 '/home' 的路由,所以它选择了{path: '**', component: PageNotFoundComponent}所以 pageNotFoundComponent 被加载

繁华开满天机

问题是命令你的路由定义数组..试试这个:const routes: Routes = [ {path: '' , redirectTo: '/home', pathMatch: 'full'}, // as first {path: 'signup', component: SignupComponent }, {path: '**', component: PageNotFoundComponent} // always as last];
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript