简体   繁体   English

如何在角度4中依赖注入之前从服务器加载路由配置?

[英]How to load route configuration from server before dependency injection in angular 4?

My top menu module doesn't know anything about routes and modules, that will be used for menu items before they load from api. 我的顶级菜单模块对路由和模块一无所知,它们在从api加载之前将用于菜单项。

var routeConfig = [
            {loadChildren: "./widget1.ts#Widget1Module", path: "widget1.ts"},
            {loadChildren: "./widget2.ts#Widget2Module", path: "widget2.ts"},
            {loadChildren: "./widget3.ts#Widget3Module", path: "widget3.ts"}
      ]; // this must be loaded before AppRoutingModule inject

@NgModule({
imports: [
    RouterModule.forRoot(
      routeConfig
    )
  ],
  exports: [ RouterModule ]
})
export class AppRoutingModule { 
};

Now i just use routeConfig as global variable and make request from pure javascript before angular imports module. 现在我只使用routeConfig作为全局变量,并在angular import module之前从纯javascript发出请求。 How to do it correctly? 怎么做正确?

As Gunter said, we can delay bootstrap method and pass some parameters like that . 作为冈特说,我们可以延迟引导方法,并通过像一些参数 But it is a wrong way in my case. 但在我的情况下,这是一种错误的方式。 In angular we can redefine routing in our application. 在角度,我们可以在我们的应用程序中重新定义路由。 So we can leave initialization parameter for RouterModule empty: 所以我们可以将RouterModule的初始化参数留空:

@NgModule({
  imports:      [ BrowserModule, RouterModule.forRoot([]), HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

But then redefine them after web api retrieve us callback with route configuration: 但是在web api通过路由配置检索回调之后再重新定义它们:

export class AppComponent implements OnInit { 
  constructor(private router: Router, private http: Http) {
  }
  public isLoaded : bool = false;
  ngOnInit() {
    this.http.get('app/routerConfig.json')
               .map((res:any) => res.json())
               .subscribe(data => {
                 this.router.resetConfig(data);
                 this.isLoaded = true;
               }, error => console.log(error));

  }
}

Here is an example in Plunker. 是Plunker中的一个例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM