Is it possible to return data to $ http.get (). Success () in service factory ()?

I have created a contact list in angular js. In the example below, I created a factory service in that I was unable to handle the $ http.post () method. Success () on the service.

angular.module('contactApp', ['ngRoute'])

.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
    when('/contactList', {
      templateUrl: 'template/contactList.cfm',
      controller: 'contList'
    }).
    when('/contactAddEdit', {
      templateUrl: 'template/contactAddEdit.cfm',
      controller: 'contactAddEdit'
    }).
    when('/contactAddEdit/:contactID', {
      templateUrl: 'template/contactAddEdit.cfm',
      controller: 'contactAddEdit'
    }).
    otherwise({
      redirectTo: '/contactList'
    });
  }
])

.controller('contList', function($scope, studentSession) {

  studentSession.getSessions().success(function(data, status) {

    $scope.members = = queryToObject(data);

  });
})

.factory('studentSession', function($http) {

  return {

    getSessions: function() {

      return $http.get('template/dbSelect.cfm');

    }

  };

});
      

Run code


+3


source to share


1 answer


You need to use then()

, not success()

, you are returning a promise from a factory:

studentSession.getSessions().then(function(data, status) {

    $scope.members = = queryToObject(data);

  }).catch(function (err) {

    console.log(err);
  });

      

If you need more support for older browsers like IE8 or Android 4.1 use this instead:



studentSession.getSessions().then(function(data, status) {

        $scope.members = = queryToObject(data);

      },function (err) {

        console.log(err);
      });

      

THEN If you really want to return the success of a promise from a factory, you need an event:

.controller('contList', function($scope, studentSession) {

  studentSession.getSessions();

  $scope.$on('session:retrievedSession', function (data) {

    console.log('Session retrieved is: ', data.response);
  });
})

.factory('studentSession', function($rootScope, $http) {

  return {

    getSessions: function() {

      return $http.get('template/dbSelect.cfm').success(function (response) {

        $rootScope.$broadcast('session:retrievedSession', {response:response});
      });

    }

  };
});

      

0


source







All Articles