angularjsangular-ui-routerdependency-resolver

AngularJS UI-Router v1.0: getting state name during resolving


I am migrating from UI-Router v0.4.x to v1.0 and I'm having an issue. Consider the following piece of code.

myApp
    .component('myComponent', {
        bindings: {
            resolveBinding: '<'
        },
        controller: class myComponentController {
            constructor() {
                // ...
            }
        },
        templateUrl: someTemplateUrl
    })
    .config(($stateProvider) => {
        $stateProvider
            .state('some-state', {
                url: '/some-state',
                component: 'myComponent',
                resolve: {
                    resolveBinding: function(DependencyResolver) {
                        let targetStateName = this.self.name
                        return DependencyResolver.doSomeThingsFor(targetStateName)
                    }
                }
            })
    })

In the new versionlet targetStateName = this.self.name will fail because this is now null, whereas before it contained information on the state it was transitioning to.

How can I get the state name in this block of code?

I was thinking about using a $transitions.onBefore hook to put the name on rootScope, and doing something like:

resolveBinding: function($rootScope, DependencyResolver) {
    let targetStateName = $rootScope.hackyStateName 
    return DependencyResolver.doSomeThingsFor(targetStateName)
}

But I feel this is ugly and I'm missing out on something easier and more elegant.


Solution

  • You can inject $transition$ into a resolve function:

    resolveBinding: function($transition$) {
      console.log($transition$.to());
    }
    

    See the $transition$ documentation.

    Does that help you?