2017-01-11 51 views
0

嗨我想拉我的角度js工廠數據到我的控制器, 請看看是否有任何問題。角度Js:如何將工廠數據拉到控制器

factory.js

.factory('History', ['$http', '$q', function ($http, $q) { 

     function history() { 

      // angular.extend(SearchOptions.getDefaults(), params, options); 
      var deferred = $q.defer(); 

      $http({ 
       method: 'GET', 
       url: '/res/orders/' + 31536427 + '/history-group' 
      }) 
      .success(function (res) { 
      // console.log(res); 

      }) 
      .error(function (err) { 
       // TODO error handler 
       deferred.reject(err); 
      }); 

      return deferred.promise; 
     } 

     return { 
      history: history 
     }; 
    }]); 

controller.js

.controller('HistoryCtrl', ['$scope', '$state', '$stateParams', 'History', function($scope, $state, $stateParams, History) { 

     History.history().then(function(res) { 
      console.log(res); 
      $scope.history = res.body; 
      console.log($scope.history); 

     }, function(err) { 
      // TODO error handler 
      console.log(err); 

     }) 
     .finally(function(err) { 

     }); 



    }]); 

回答

3

您需要將在 '歷史記錄' 工廠爲下文成功函數的響應:

.success(function (res) { 
    // console.log(res); 
    deferred.resolve(res); 
}) 
1

問題你的代碼是在成功回調函數中獲取數據後,你沒有解決承諾。默認返回一個承諾在角

  1. $http服務:解決它作爲.success回調函數如下圖所示:

    deferred.resolve(res); 
    

    幾點來提高你的代碼。因此,您不必明確構建promise使用$q這是一個反模式Deferred anti-pattern)。從服務本身返回$http對象將執行 作業。在您的代碼中,執行return $http()相當於return deferred.promise()

  2. .success.error回調棄用的AngularJsDeprecation Notice)的最新版本(1.6)。使用它們的缺點是它們不能鏈接,因爲它們忽略了返回值。因此,最好使用.then來代替。

應用上述變化,你的服務可以重構爲以下:

.factory('History', ['$http', function ($http) { 

    function history() { 
     return $http({ 
        method: 'GET', 
        url: '/res/orders/' + 31536427 + '/history-group' 
       }) 
       .then(successCallback, errorCallback); 
    } 

    function successCalback (res) { 
     return res; 
    } 

    function errorCalback (err) { 
     return err; 
    } 

    return { 
     history: history 
    }; 
}]); 
相關問題