AngularJS: Performing $http request inside custom service and returning data

前端 未结 1 2033
小蘑菇
小蘑菇 2021-01-31 06:52

I have defined a custom http service in angular that looks like this:

angular.module(\'myApp\')
  .factory(\'myhttpserv\', function ($http) {

  var url = \"http         


        
相关标签:
1条回答
  • 2021-01-31 07:22

    Option 1 - Use promise API

    angular.module('myApp').factory('myhttpserv', function ($http) {
      return $http.get('http://my.ip.address/getUser?u=3', { cache: true });
    });
    

    Controller:

    angular.module('myApp').controller('myCtrl', function ($scope, myhttpserv) {
         myhttpserv.then(function(response){
             console.log(response.data);
         });     
    });
    

    Option 2 - Using route resolve

    angular.module('myApp', ['ngRoute']).config(['$routeProvider',
      function($routeProvider) {
        $routeProvider.
          when('/myCtrl', {
            templateUrl: 'myView.html',
            controller: 'myCtrl',
            resolve: {
            load: function (myhttpserv) {
                return myhttpserv;
            }
          });
      }]);
    

    Service:

    angular.module('myApp').factory('myhttpserv', function ($http) {
          var data = {};
          var url = "http://my.ip.address/";
          var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
                    data = response.data;
                });
          return data;
        });
    

    Controller:

     angular.module('myApp')
      .controller('myCtrl', function ($scope, myhttpserv) {
    
          console.log(myhttpserv.data.var1);
          console.log(myhttpserv.data.var1);
          etc...
    
    });
    

    Option 3 - Use $interval service

    angular.module('myApp').factory('myhttpserv', function ($http) {
      var data = {};
      var url = "http://my.ip.address/";
      var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
                data = response.data;
            });
      return data;
    });
    

    Controller:

    angular.module('myApp').controller('myCtrl', function ($scope, $interval, myhttpserv) {
          $scope.intervalPromise = $interval(function(){
              if (Object.keys(myhttpserv.data).length!=0)
              {
                  console.log(myhttpserv.data);
                  $interval.cancel($scope.intervalPromise);
              }
          }, 100);    
    });
    
    0 讨论(0)
提交回复
热议问题