簡體   English   中英

我應該如何將數據從異步服務設置到控制器$ scope中?

[英]How should I set data from an asynchronous service into a controller $scope?

我頁面中的所有服務器數據訪問均由我的RequestFactory提供程序執行。 (RequestFactory使用$ http執行實際的服務器調用。)

我的控制器作用域對從RequestFactory返回的數據列表進行了引用。

我的問題是,由於RequestFactory調用是異步的,並且RequestFactory不(也不應)訪問控制器作用域,因此RequestFactory將數據移交給控制器的正確方法是什么?

var requestFactory = {};
angular.module("myApp").factory("RequestFactory", function($http) {
    requestFactory.fetch = function() {
        $http.get(url).
            success(function(data) {
                controller.setData(data)
            }).
            error(function(data, status) {
                console.info("fetch Failed. Error code: " + status + " Url:" + url);
            }).finally(function() {
                controller.setSubmitting(false);
            });
    };
    return requestFactory;
});

您可以執行以下操作:

服務

(function(){

  function Service($http){

    function get(){
      //We return a promise
      return $http.get('path_to_url');
    }

    var factory = {
      get: get
    };

    return factory;

  }

  angular
    .module('app')
    .factory('Request', Service);

})();

控制者

(function(){

function Controller($scope, $q, Request) {

  var defer = $q.defer();

  //Call our get method from the Request Factory
  Request.get().then(function(response){
    //When we get the response, resolve the data
    defer.resolve(response.data);
  });

  //When the data is set, we can resolve the promise
  defer.promise.then(function(data){
    console.log(data);
  });

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

如您所知, $http服務會返回諾言,因此之后,您可以輕松地將它們組合在一起。

您應該從工廠退還諾言。 請參見下面的代碼段。

.factory("RequestFactory", function($http) {
   return {
     fetch : function() {
        return $http.get(url).then(function(result) {
           return result.data;
        });
     }
   }
});

在您的控制器中,您應該使用like

.controller('MainCtrl', function($scope, RequestFactory) {
  RequestFactory.fetch().then(function(data) 
     $scope.foo = data;
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM