I am looking to have two separate controllers trigger different functions once a set of promises are resolved within a service. I want to avoid making multiple HTTP requests, opting instead for just one request.
The scenario is as follows: a service makes a request and receives a promise. Controller1 should be able to detect when this promise resolves and then execute some code. Subsequently, Controller2 should also be able to pick up on the resolution of the same promise and run its own set of code. Essentially, I am aiming for multiple 'then()' methods triggering off the same promise but in different files. How can this be achieved?
While most examples demonstrate a single controller responding to a resolved promise, I need guidance on handling multiple controllers listening for the same resolution of a promise.
For reference, here is an excerpt from an article that I found insightful (I will be adding a 'mother controller' to better explain my specific case; it is important that the son service only makes the HTTP call once):
Son Service:
app.factory('SonService', function ($http, $q) {
return {
getWeather: function() {
// Utilizing the $http API based on the deferred/promise structure from $q service
// resulting in a promise being returned by default
return $http.get('http://fishing-weather-api.com/sunday/afternoon')
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return $q.reject(response.data);
}
}, function(response) {
return $q.reject(response.data);
});
}
};
});
Father Controller:
var makePromiseWithSon = function() {
SonService.getWeather()
.then(function(data) {
if (data.forecast==='good') {
prepareFishingTrip();
} else {
prepareSundayRoastDinner();
}
}, function(error) {
prepareSundayRoastDinner();
});
};
Mother Controller:
var makePromiseWithSon = function() {
SonService.getWeather()
.then(function(data) {
if (data.forecast==='good') {
workInTheGarden();
} else {
sweepTheHouse();
}
}, function(error) {
sweepTheHouse();
});
};