core
core

Reputation: 33087

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?

Upvotes: 1

Views: 834

Answers (3)

Denis  Ejov
Denis Ejov

Reputation: 1

For me didn't work $q.resolve, but you can use instead $q.when

this.fetchChartModel = function() {
    return $http.get(fullUrlPath)
    .then(function(rawData) {
        return $q.when(chartModelService.translate(rawData));
    });
};

Upvotes: 0

MBielski
MBielski

Reputation: 6620

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.

Upvotes: 3

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

just move your code ;)

this.fetchChartModel = function() {
    return $http.get(fullUrlPath)
    .then(function(rawData) {
        return $q.resolve(chartModelService.translate(rawData);)
    });
};

that should do it just make sure you include $q service in your dependencies

Upvotes: 0

Related Questions