0

In UI-Router's RootModule.otherwise we can specify where to redirect the user if the user is opening a URL that the application doesn't recognize. I have been using the simple format, just a string specifying the target state's name:

@NgModule({ imports: [UIRouterModule.forRoot({ states: [ { name: "home", url: "/home", component: HomeComponent } ], otherwise: "/home" })], exports: [UIRouterModule], providers: [] }) export class AppRoutingModule { } 

But now I need to get data by calling a service to determine which target state I should redirect the user. I tried the function format of the otherwise hoping to be able to get access to my service through the injector:

otherwise: (matchValue, url: UrlParts, router: UIRouter) => { // this didn't work, router.globals.transition is not available const userPrefSvc = router.globals.transition.injector().get(UserPreferenceService); } 

But it didn't work, I can't find a way to get hold of the injector.

Is it possible to access services from the otherwise function?

1 Answer 1

1

This answer is actually from Christopher Thielen.

Setting the otherwise function can also be done in config function, where we have access to injector:

@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 { } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.