redrom
redrom

Reputation: 11632

AngularJS Async request method service return data using promise

I have this global method in custom service.

/**
 * Global service class for making http requests.
 */
app.service('API', function ($http) {

    /**
     * Process remote POST request to give URL with given params
     * @param {String} url
     * @param {String} POST params
     * @return {JSON}  response from server
     */
    this.doHttpRequest = function (type, url, params) {
        $http({
            method: type,
            url: url,
            data:params,
            timeout:2000,
            headers: {"Content-Type": "application/json"}
        })
            .success(function (data, status, headers, config) {
                // successful data retrieval
                console.log("request success");
                console.log("state: "+status);
                return data;
            })
            .error(function (data, status, headers, config) {
                // do some stuff
            });
    };
});

||

Problem is that, if i'm trying to get response from my cotroler method i get always just undefined.

/**
 * Test of service
 */
$scope.serviceTest = function () {

    var requestParams = {
        "token":'test',
        "data":{
            "test":'test'
        }
    };

    var url = $rootScope.apiBaseUrl + "user/update";

    var result = API.doHttpRequest("POST", url, requestParams);
    // HERE I GET UNDEFINED 
    console.log("Result is: " + result);
};

I red about promises but without luck to get data back.

Question is:

How i should modify my code to obtain returned values?

Thanks for any help

Upvotes: 0

Views: 967

Answers (2)

dark_ruby
dark_ruby

Reputation: 7866

modify your service so it doesn't call anything on a promise returned by $http, also notice return.

app.service('API', function ($http) {

    /**
     * Process remote POST request to give URL with given params
     * @param {String} url
     * @param {String} POST params
     * @return {JSON}  response from server
     */
        this.doHttpRequest = function (type, url, params) {
          return $http({
            method: type,
            url: url,
            data:params,
            timeout:2000,
            headers: {"Content-Type": "application/json"}
        });

    };
});

then when you consume your service it will return a promise which you can run success and error on

API.doHttpRequest("POST", url, requestParams)
            .success(function (data, status, headers, config) {
                // successful data retrieval
                console.log("request success");
                console.log("state: "+status);
                // do something with data
            })
            .error(function (data, status, headers, config) {
                // do some stuff
            });

Upvotes: 1

maurycy
maurycy

Reputation: 8465

Here is my little working code that uses promises with $http request

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, dataService) {
  dataService.then(function (data) {
    $scope.data = data
  })
});

app.controller('SecondCtrl', function($scope, dataService) {
  dataService.then(function (data) {
    $scope.secData = data
  })
});

app.service('dataService', function ($http, $q){
  var defferer = $q.defer()

  $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').success(function (data){
    defferer.resolve(data)
  })

  return defferer.promise
})

http://plnkr.co/edit/o3W6U9?p=info

Upvotes: 0

Related Questions