首页 > 解决方案 > Angular - 在 Angular 中创建路由时出错

问题描述

我是 Angular 的新手,我想在我的 Angular 应用程序中创建路由,但在声明路由服务时 app.module.ts 中出现错误。我对我在 RouterModule.forRoot() 括号中写的内容感到困惑

error: error TS2304: Cannot find name 'Routes'.RouterModule.forRoot(Routes)

route.service.ts:

import { Injectable } from '@angular/core';
import { Routes } from '@angular/router';
import { ParentComponent } from '../parent/parent.component';
import { from } from 'rxjs';
import { ChildComponent } from '../child/child.component';

const appRoutes:Routes=[

  {path:"parent",component:ParentComponent},
  {path:"child",component:ChildComponent}
]
@Injectable({
  providedIn: 'root'
})
export class RoutesService {

  constructor() { }
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// import {MessageserviceService} from './services/messageservice.service'
import {MessageserviceService} from './services/messageservice.service';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ParentComponent } from './parent/parent.component';
import { ChildComponent } from './child/child.component';
import { RoutesService } from './services/routes.service';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [
    AppComponent,
    ParentComponent,
    ChildComponent,
    
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    RouterModule.forRoot(appRoutes)  //i got error in this line, 
    

  ],
  providers: [MessageserviceService,RoutesService],
  bootstrap: [AppComponent]
})
export class AppModule { }

标签: angulartypescript

解决方案


如果您尝试将路由与主模块分开,只需创建一个 routingModule,就像在 Angular 文档中所做的那样:https ://angular.io/tutorial/toh-pt5#add-the-approutingmodule

顺便说一句,您的代码无法正常工作。如果要将“appRoutes”保留在服务文件中,请使用

export const appRoutes: Routes = [

  {path:"parent",component:ParentComponent},
  {path:"child",component:ChildComponent}
];

但是,您的服务毫无用处。

或者将 appRoutes 移动到您的服务中,并将其声明为您的服务的属性。

在这两种情况下,请确保在 AppModule 中导入 appRoutes。

但再一次,这并不是在“常规”角度应用程序中处理路由的真正方法。


推荐阅读