我有angular 6应用程序。我有获取动态路由的要求,其逻辑已排序。我有AppRoutingService类,该类具有方法getAppRoutes()返回静态路由集合。我需要将其称为app RouterModule.forRoot(...),目标是可以使用服务类设法注入静态路由,然后可以在此静态列表中从数据库组装动态路由。
这样做会出错。
Uncaught TypeError: Cannot read property 'appRoutingService' of undefined
at main.js:1055
at Module../src/app/modules/application/app-routing.module.ts (main.js:1065)
at __webpack_require__ (runtime.js:84)
import { AppRoutingService } from './services/routing/app-routing-service';
@NgModule({
imports: [
RouterModule.forRoot(this.appRoutingService.getAppRoutes()) // here i need to inject appRoutingService method... need help here....???
],
exports: [
RouterModule
]
})
export class AppRoutingModule {
constructor(
private router:Router,
private appRoutingService: AppRoutingService
) {
}
}
@Injectable()
export class AppRoutingService{
public RouteCollection: Routes = [
{
path:'',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: '',
component: WebLayoutComponent,
children:[
{
path:'dashboard',
loadChildren: '../dashboard/dashboard.module#DashboardModule'
},
{
path:'survey',
loadChildren: '../survey/survey.module#SurveyModule'
}
]
},
{
path:'**',
component:PageNotFoundComponent
}
];
public getAppRoutes(): Route[]
{
return this.RouteCollection;
}
}
答案 0 :(得分:1)
您在错误的位置使用了关键字“ this”。在这种情况下,没有“ this”,因为它在类之外。由于“ this” === undefined,因此错误的原因变得很清楚,因为您正试图从undefined中获取appRoutingService。
#include<iostream>
并设置AppRoutingService方法和变量为静态。
@NgModule({
imports: [
RouterModule.forRoot(AppRoutingService.getAppRoutes()) // here i need
to inject appRoutingService method... need help here....???
],
exports: [
RouterModule
]
})