Return http data from Angular service

后端 未结 2 1736
南方客
南方客 2021-01-19 16:43

I\'m sure this will be an easy one for any Angular/Javascript experts. I have a service that makes a call to an API to get some data:

app.service(\"GetDivisi         


        
2条回答
  •  不思量自难忘°
    2021-01-19 17:43

    You can return empty object from your service and populate it once you receive the response. That is the way $resource service do it. It also allows to avoid additional logic in controller.

    This will work because reference to data object that is put into the scope remains the same all the time and $http service starts digest cycle once response is returned. Therefore the change in the scope.division will be immediately detected and view will be updated accordingly.

    JavaScript

    var app = angular.module('app',[]);
    
    app.service("GetDivision", ["$http", function($http){
    
      var data = {};
    
      this.division = function(divisionNumber){
        $http.get("division", {division:divisionNumber}).success(function(responseData){
          angular.extend(data, responseData);
        });
        return data;
      } 
    
    }]);
    
    app.controller('ctrl', ['$scope', 'GetDivision', function ($scope, GetDivision) {
      $scope.division = GetDivision.division(1);
    }]);
    

    HTML

    
      

    {{division.text}}

    Live Demo: http://plnkr.co/edit/H31mSaXiiCiVG9BA9aHK?p=preview

提交回复
热议问题