diff --git a/angular-ui/angular-ui-router-tests.ts b/angular-ui/angular-ui-router-tests.ts index 5a9c4ad6c..d7dbe7183 100644 --- a/angular-ui/angular-ui-router-tests.ts +++ b/angular-ui/angular-ui-router-tests.ts @@ -71,3 +71,42 @@ myApp.config(( } }); }); + +interface IUrlLocatorTestService { + currentUser: any; +} + +// Service for determining who the currently logged on user is. +class UrlLocatorTestService implements IUrlLocatorTestService { + static $inject = ["$http", "$rootScope", "$urlRouter"]; + + constructor( + private $http: ng.IHttpService, + private $rootScope: ng.IRootScopeService, + private $urlRouter: ng.ui.IUrlRouterService + ) { + $rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event)); + } + + public currentUser: any; + + private onLocationChangeSuccess(event: ng.IAngularEvent) { + if (!this.currentUser) { + // If the current user is unknown, halt the state change and request current + // user details from the server + event.preventDefault(); + + // Note that we do not concern ourselves with what to do if this request fails, + // because if it fails, the web page will be redirected away to the login screen. + this.$http({ url: "/api/me", method: "GET" }).success((user: any) => { + this.currentUser = user; + + // sync the ui-state with the location in the browser, which effectively + // restarts the state change that was stopped previously + this.$urlRouter.sync(); + }); + } + } +} + +myApp.service("urlLocatorTest", UrlLocatorTestService);