如何以角度动态组合路线?

问题描述 投票:1回答:2

假设我有一个服务来获取以json格式化的路径数组,如下所示:

[{
    "path": "routeName"
    "component": "MyComponent"
}]

当然,“我的组件”将作为字符串检索。现在我想将此数组转换为路由模块的路由。如何将“MyComponent”转换为MyComponent类?

这样做的目的是让我的前端不知道它是什么。要添加新的路由和组件,我只需要在服务器上的文件中添加一个新条目,并使其与我在angular app中创建的组件名称相匹配。

angular angular2-routing
2个回答
2
投票

这是app模块

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,它返回组件对键,如:

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

0
投票

步骤1:将路由器注入app模块

第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 });
}}
© www.soinside.com 2019 - 2024. All rights reserved.