angular - 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 { }
解决方案
如果您尝试将路由与主模块分开,只需创建一个 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。
但再一次,这并不是在“常规”角度应用程序中处理路由的真正方法。
推荐阅读
- amazon-web-services - 基于 cookie 存在的云端缓存
- html - 如何从新文本字段中获取元素?
- windows - 如何在bat中获取特定路径下的lib文件列表?
- python - PowerTransform inverse_transform 未准确反转
- amazon-web-services - GitHub 操作触发 cypress e2e 测试的批处理代码构建不起作用
- angular - mat-optgroup 不适用于 compareWith
- performance - MySQL 8.0.18:关键效率 0.0%
- java - 是否有任何 API 可以在 java 中格式化货币值?
- pagination - 与客户端同步服务器端分页
- c++ - C++ 捕获错误“抛出 'std::out_of_range' 的实例”