简体   繁体   中英

Angular controller service promise not working

I want to wait for an http response before exiting angular controller. I have written the following code. But id doesn't work as the controller still exits before the http call is returned. Can anyone help me out to fix this? Thanks in advance.

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

app.factory('MyService', function ($http) {
        return $http.get('/api/endpoint').then(function(res){
          return res.data;
        });
    });

app.controller('MyController', ['$scope', '$http', 'MyService', function($scope, $http, MyService){
  MyService.then(function(data){
    $scope.myVarialbe = data;
  })
}]);
I would write this as below.
    'use strict';

    (function () {

        function MyService($http) {

        function getService() {

            var url = yourURL;
            return $http({ method: 'GET', cache: false, url: url });
        }

            return {
                getService: getService

            };
        }

        angular.module('app')
            .factory('MyService', MyService);
    }());

controller code:

      MyService.getService().then(function(response) {

      });

You can use like this factory just return request response promise and in controller use .then on returned promise .

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

app.factory('MyService', ['$http',function($http) {
    return {
       getData: function() {
          return $http.get('/api/endpoint');
       }
    };
}]);

app.controller('MyController', ['$scope', '$http', 'MyService', function($scope, $http, MyService){
   MyService.getData().then(function(response){
     $scope.myVarialbe = response.data;
   });
}]);

Use $q is better.

Eg:

app.factory('MyService', ['$http', '$q', function($http, $q) {
return {
   getData: function() {
      var deferred = $q.defer();
      $http.get('/api/endpoint')
          .then( function(resp) {
              deferred.resolve( resp.data );
           });
      return deferred.promise;
     }
   };
}]);

app.controller('MyController', ['$scope', 'MyService',function($scope, MyService){
    MyService.getData().then(function(data){
        $scope.myVarialbe = data;
    })
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM