2

I have a single page app built using AngularJS. When the page first loads, there are two controllers that execute and these are 'Controller1' and 'Controller2'.

  • Each of them needs to make a call to the same WebAPI in order to meet its logic requirements.
  • Also, 'Controller1' code executes first, but due to the async nature of the code, 'Conroller2' code starts to execute before the Controller1 call to WebAPI has returned successfully.

Question: How can I make sure that only Controller1 makes the call to WebAPI, so that Controller2 simply uses the call in Controller1 rather than making a repeated call?

Controller1

dashboardDataService.getAllDashboards().then(onDashboardListReceived)

Controller2

dashboardDataService.getAllDashboards().then(onDashboardListReceived)

1 Answer 1

5
.service('dashboardDataService', function($http){
    var dashboardDataServiceScope = this;

    var allDashboardsPromise = false;

    dashboardDataServiceScope.getAllDashboards = function(){
        if(!allDashboardsPromise){
            allDashboardsPromise = $http.post(...);
        }
        return allDashboardsPromise;
    };
});

What this will do will create a promise the first time, and then every time something else calls it will just return the same promise. So you can have multiple hooked into one.

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't ' return allDashboardsDeferred.promise' be just ' return allDashboardsDeferred', since allDashboardsDeferred becomes a promise when used with $http.post(...).then(...)?
You're right, I had initially wired it up with $q :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.