假设我有一个服务可以像这样提取以json格式格式化的路径数组:
[{
"path": "routeName"
"component": "MyComponent"
}]
当然,“ MyComponent”将作为字符串检索。现在,我想将此数组转换为路由模块的Routes。如何将“ MyComponent”转换为MyComponent类?
这样做的目的是使前端不知道它是什么。要添加新的路线和组件,我只需要在服务器上的文件中添加一个新条目,并使它与我在angular应用程序中创建的组件名称匹配。
答案 0 :(得分:2)
这是应用模块
export const routes: Route[] = [
];
@NgModule({
declarations: [
AppComponent,
ErrorHandleComponent,
FilterComponent,
CreateComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(routes),
// AppRoutingModule,
HttpClientModule
],
entryComponents: [
CreateComponent,
FilterComponent,
ErrorHandleComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,请确保您具有键值对obj,该键值对obj将针对键的组件返回:
import { CreateComponent } from '../create/create.component';
import { FilterComponent } from '../filter/filter.component';
import { ErrorHandleComponent } from '../error-handle/error-handle.component';
export const components = {
'CreateComponent': CreateComponent,
'FilterComponent': FilterComponent,
'ErrorHandleComponent': ErrorHandleComponent,
};
然后将此代码放入app.component.ts文件
constructor(private api: ApiService, private router: Router) {
}
getRoute() {
this.api.get_route().subscribe(res => {
res.forEach(element => {
// components key value pair obj
element.component = components[element.component];
routes.push(element);
});
this.rlist = routes;
this.router.resetConfig(routes);
});
答案 1 :(得分:0)
第1步:将路由器注入应用模块
第2步:您可以随意更改router.config
@
NgModule({
declarations: [
HomeComponent
...
],
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: '**', redirectTo: 'home' }
])
],
providers: []})
export class AppModule {
constructor(router: Router) {
router.config.unshift({ path: 'new_path', component: NewComponent });
}}