【问题标题】:Cannot match any routes. URL Segment:无法匹配任何路由。网址段:
【发布时间】:2018-12-01 23:02:59
【问题描述】:

我是 Angular 新手,正在尝试配置路由,但出现此错误:

Error: Cannot match any routes. URL Segment: 'news'

这是我的应用路由模块:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import{ RouterModule, Routes} from'@angular/router';
import{ myRoutes } from'./routes';

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

我的路线文件:

import{ Routes} from '@angular/router';
import { HomepageComponent } from '../homepage/homepage.component';
import { NewsComponent } from '../news/news.component';

export const myRoutes: Routes= [
    { path: 'homepage', component: HomepageComponent},
    { path: 'news', component: NewsComponent},
    { path: '', redirectTo: '/homepage', pathMatch: 'full' }
    ];

我的 app.module.ts 文件:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { HomepageComponent } from './homepage/homepage.component';
import { NewsComponent } from './news/news.component';
@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    HomepageComponent,
    NewsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFontAwesomeModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

最后,我的 app.component.html 文件:

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

我在尝试访问主页视图时遇到了同样的错误。

【问题讨论】:

  • 你在导入这些路由吗?
  • 除非您不导入路线,否则我看不到任何问题
  • 在哪里?我用这一行导入它们: import{ myRoutes } from'./routes';

标签: angular


【解决方案1】:

您可以尝试将您的路线放在文件app-routing-module 上吗?

在这里找到一点stackblitz

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

import { NewsComponent } from './news/news.component';
import { HomepageComponent } from './homepage/homepage.component';

const routes: Routes = [
  { path: 'homepage', component: HomepageComponent},
  { path: 'news', component: NewsComponent},
  { path: '', redirectTo: '/homepage', pathMatch: 'full' }
];

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

【讨论】:

  • 我试过了,还是不行。您认为与角度版本有关吗?我正在使用 7.0.6
  • 不要认为与你的版本有关,因为我将我的 stackblitz 更新到了最新版本,我对它没有任何问题
  • @araujo 您是否尝试重新构建您的项目,或者我的意思是停止 ng serve 并重新运行应用程序
猜你喜欢
  • 2020-04-14
  • 2018-03-08
  • 2017-03-01
  • 2018-09-01
  • 2017-08-10
  • 2017-11-13
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
相关资源
最近更新 更多