Angular2中,使用Service获取应用路由

In Angular2, Use Service to get application routes

我有 angular 6 个申请。我需要获取动态路由,其逻辑已排序。我有 AppRoutingService class,它有方法 getAppRoutes() 返回静态路由集合。我需要将其称为应用程序 RouterModule.forRoot(...),objective 如果可以使用服务 class 设法注入静态路由,那么我可以 assemble 来自此静态列表中的数据库。

这样做时出现错误。

错误

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)

应用路由class

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
 ) { 
 }
}

应用路由服务class

@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;
 } 
}

您在错误的地方使用了关键字 "this"。在那个上下文中没有 "this",因为它在 class 之外。由于 "this" === undefined,那么错误背后的原因就很清楚了,因为你正试图从 undefined 中获取 appRoutingService。

@NgModule({
imports: [
   RouterModule.forRoot(AppRoutingService.getAppRoutes()) // here i need 
           to inject appRoutingService method... need help here....???
  ],
  exports: [
    RouterModule
  ]
})

并将 AppRoutingService 方法和变量设为静态。

public static 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 static getAppRoutes(): Route[]
{
   return AppRoutingService.RouteCollection;
}