App_Initializer无法使用UI路由器

时间:2018-02-01 16:22:03

标签: angular

UI-Router在执行App_Initializer函数之前触发config部分中定义的路由更改。在下面的示例中,在resolveFn结算之前触发了家庭状态App_Initialzer's

如何解决这个问题?

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    routingComponents
  ],
  imports: [
    BrowserModule,
    UIRouterModule.forRoot(
      { states: appRoutes, 
        useHash: true ,
        config: uiRouterConfigFn
      }
    ),
  ],
  providers: [
    {
        provide: APP_INITIALIZER,
        useFactory: test,
        multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

function test(): Function {
  return () => delay();
}

function delay(){
  var deferred = new Deferred<any>();
  console.log("Initialization started: " + new Date());
  setTimeout(() => {
    console.log("Initialization Done: " + new Date());
    deferred.resolve();
  }, 5000); // Wait 3s then resolve.
  return deferred.promise;
}

app.routes.ts

export const routingComponents = [
    HomeComponent
  ];


let home = {
    name: 'home',
    url: '/home',
    component: HomeComponent,
    resolve:[
      {
        token: 'te',
        resolveFn:($state: StateService) =>{
          var deferred = new Deferred<any>();
          console.log("testing Home Component");
          deferred.resolve();
          return deferred.promise;
        }
      }
    ]
  }

  export const appRoutes = [
    home
  ];

  export function uiRouterConfigFn(router: UIRouter, injector: Injector) { 
    // If no URL matches, go to the `hello` state by default
    router.urlService.rules.otherwise({ state: 'home' });
  }

1 个答案:

答案 0 :(得分:1)

对于其他需要解决此问题的人,您可以使用UIRouterModule的{​​{1}}方法阻止路由在deferIntercept()解决之前初始化。 (Per Christopher Thielen(@ UIRouter):https://github.com/ui-router/angular/issues/206

我可以通过在APP_INITIALIZER中将deferIntercept设置为true来解决此问题:

app.module

^此部分可防止路由初始化。

然后需要调用@NgModule({ imports: [ /* Other modules ... */ UIRouterModule.forRoot({ states: [ /* States (routes) ...*/ ], config: uiRouterConfigFn, deferIntercept: true, // Allows APP_INITIALIZER to complete before routing useHash: true, }), ], declarations: [ /* Component declarations ... */ ], providers: [ AppConfig, { provide: APP_INITIALIZER, useFactory: initResources, deps: [AppConfig, TranslationConfigModule, UIRouter], multi: true, }, ], bootstrap: [AppComponent], }) listen()来恢复路由器:

sync()