AngularJS : returning data from service to controller

一世执手 提交于 2019-11-30 07:18:23

You should return promise from getResponders function, & when it gets resolved it should return response.data from that function.

Factory

var myService = angular.module("xo").factory("myService", ['$http', function($http) {
    return {
        getResponders: function() {    
            return $http.get('myUrl')
            .then(function(response) {
                console.log("coming from servicejs", response.data);
                //return data when promise resolved
                //that would help you to continue promise chain.
                return response.data;
            });
        }
    };
}]);

Also inside your controller you should call the factory function and use .then function to get call it when the getResponders service function resolves the $http.get call and assign the data to $scope.gotData

Code

 $scope.goData = function(){
     myService.getResponders.then(function(data){
          $scope.gotData = data;
     });

 };
RANDRIAMILASOA Hajaniaina Stan

This is an example how I did for my project, it work fine for me

var biblionum = angular.module('biblioApp', []);//your app
biblionum.service('CategorieService', function($http) {


    this.getAll = function() {

        return $http({
            method: 'GET',
            url: 'ouvrage?action=getcategorie',
            // pass in data as strings
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}  // set the headers so angular passing info as form data (not request payload)
        })
                .then(function(data) {

                    return data;


                })


    }


});

biblionum.controller('libraryController', function($scope,CategorieService) {
  
    var cat = CategorieService.getAll();
    cat.then(function(data) {
        $scope.categories = data.data;//don't forget "this" in the service
    })

  });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!