core core - 1 month ago 16
Javascript Question

Angular promise: intercept "then"

Right now I have an Angular service named

chartModelService
with this method on it:

this.fetchChartModel = function() {
return $http.get(fullUrlPath);
};


And I have an Angular controller that consumes this data:

chartModelService.fetchChartModel().then(function(rawData) {
var chartData = chartModelService.translate(rawData);
$scope.populateChart(chartData);
});


I would like to perform the
chartModelService.translate(data)
within the
chartModelService
instead of the controller using the service. In other words, I would like to change to controller to the code below, where the
chartData
it receives has already been translated:

chartModelService.fetchChartModel().then(function(chartData) {
$scope.populateChart(chartData);
});


How can I change
chartModelService.fetchChartModel()
so that it performs
translate()
before returning the promised data?

Answer

Change this:

this.fetchChartModel = function() {
    return $http.get(fullUrlPath);
};

To This:

this.fetchChartModel = function() {
    var defObj = $q.defer();

    var fetch = $http.get(fullUrlPath);
    fetch.then(function(data){
        defObj.resolve(chartModelService.translate(data));
    });

    return defObj.promise;
};

(with the appropriate DI on your service, of course)

This will init the data fetch and return a promise that contains your translated data when it has been fulfilled.

Comments