r3plica
r3plica

Reputation: 13367

AngularJs ui-router success transition get the controller

I have created a service that is to run any http requests that have been requested. This runs in the ui-router onSuccess hook and looks like this:

$transitions.onSuccess({}, function() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
    console.log('%cwe have completed a transition', 'color: green;');
    httpQueueService.process();
});

The problem with this is that the controller is initialized after this hook, so I can't capture the http requests without adding a timeout:

function process() {
    $timeout(() => {
        let t = angular.copy(queue);
        console.log('processing', t, t.length);
        queue.forEach((task) => invoke(task));
    }, 500);
}

I know the timeout is only half a second and I could probably reduce that even futher, but it doesn't seem right. It would be better if I could get the controller that has been initialized directly from the success hook.

Is there a way of doing this?

I did try by looking at the transition object in the success hook:

$transitions.onSuccess({}, function(transition) {
    console.log(transition);
});

But that doesn't appear to have the controller there

Upvotes: 3

Views: 499

Answers (1)

Andrew Adam
Andrew Adam

Reputation: 1582

What you are looking for is the 'resolve' option of the ui-router's states. You are trying to asynchronously load data (from your httpQueueService) to the new state's controller if I understood your description correctly. I suggest you take a look at the official ui-router documentation, especially the tutorials. Obviously you can skip most of it, so starting from the second: https://ui-router.github.io/ng1/tutorial/hellosolarsystem seems feasible for you.

Basically it handles the asynchronous nature of what you are doing - without adding any exact, hard-coded timeout.

Here is another great article which I found helpful when dealt with async queries on transitions: https://medium.com/opinionated-angularjs/advanced-routing-and-resolves-a2fcbf874a1c

I hope this helps, however, if you have any more specific issue then let us know!

Upvotes: 2

Related Questions