在 UI-路由器的 `otherwise` 函数中访问服务
Accessing services in UI-Router's `otherwise` function
在 UI-Router 的 RootModule.otherwise
中,我们可以指定在用户打开应用程序无法识别的 URL 时将用户重定向到何处。我一直在使用简单的格式,只是一个指定目标状态名称的字符串:
@NgModule({
imports: [UIRouterModule.forRoot({
states: [
{
name: "home",
url: "/home",
component: HomeComponent
}
],
otherwise: "/home"
})],
exports: [UIRouterModule],
providers: []
})
export class AppRoutingModule { }
但现在我需要通过调用服务来获取数据以确定我应该将用户重定向到哪个目标状态。我尝试了 otherwise
的函数格式,希望能够通过注入器访问我的服务:
otherwise: (matchValue, url: UrlParts, router: UIRouter) => {
// this didn't work, router.globals.transition is not available
const userPrefSvc = router.globals.transition.injector().get(UserPreferenceService);
}
但是没用,我找不到办法拿到注射器。
是否可以从 otherwise
功能访问服务?
这个答案其实来自Christopher Thielen.
设置otherwise
函数也可以在配置函数中完成,我们可以在其中访问注入器:
@NgModule({
imports: [UIRouterModule.forRoot({
states: [
{
name: "home",
url: "/home",
component: HomeComponent
}
],
config: (uiRouter: UIRouter, injector: Injector, statesModule: StatesModule) => {
let userPrefSvc = injector.get(UserPreferenceService);
uiRouter.urlService.rules.otherwise((matchValue, url, router) => {
// ...
router.stateService.go("home");
// or
return "/home";
});
}
})],
exports: [UIRouterModule],
providers: []
})
export class AppRoutingModule { }
在 UI-Router 的 RootModule.otherwise
中,我们可以指定在用户打开应用程序无法识别的 URL 时将用户重定向到何处。我一直在使用简单的格式,只是一个指定目标状态名称的字符串:
@NgModule({
imports: [UIRouterModule.forRoot({
states: [
{
name: "home",
url: "/home",
component: HomeComponent
}
],
otherwise: "/home"
})],
exports: [UIRouterModule],
providers: []
})
export class AppRoutingModule { }
但现在我需要通过调用服务来获取数据以确定我应该将用户重定向到哪个目标状态。我尝试了 otherwise
的函数格式,希望能够通过注入器访问我的服务:
otherwise: (matchValue, url: UrlParts, router: UIRouter) => {
// this didn't work, router.globals.transition is not available
const userPrefSvc = router.globals.transition.injector().get(UserPreferenceService);
}
但是没用,我找不到办法拿到注射器。
是否可以从 otherwise
功能访问服务?
这个答案其实来自Christopher Thielen.
设置otherwise
函数也可以在配置函数中完成,我们可以在其中访问注入器:
@NgModule({
imports: [UIRouterModule.forRoot({
states: [
{
name: "home",
url: "/home",
component: HomeComponent
}
],
config: (uiRouter: UIRouter, injector: Injector, statesModule: StatesModule) => {
let userPrefSvc = injector.get(UserPreferenceService);
uiRouter.urlService.rules.otherwise((matchValue, url, router) => {
// ...
router.stateService.go("home");
// or
return "/home";
});
}
})],
exports: [UIRouterModule],
providers: []
})
export class AppRoutingModule { }