2016-06-30 29 views
3

我有單獨的$http GET請求將字典從控制器請求到單獨的文件中,作爲服務。我嘗試過尋找這個,但我還沒有找到eglibe的提示。請支持。

以下是文件:

app.js:

require('angular'); 
window.jQuery = $ = require('jquery'); 

var bootstrap = require('bootstrap-sass'); 
var HomeController = require('./controllers/HomeController'); 
var dictionaryService = require('./services/dictionary.service'); 

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

app.controller('Controller', [ '$scope', '$http', '$log', HomeController ]); 

controller.js

module.exports = function ($scope, $http, $log) { 

    console.log('Hello from CTRL'); 
    $scope.message = 'Two birds killed by stone!'; 

    $http({ 
     method: 'GET', 
     url: '/wsrp_crm/memcached' 
    }).then(function successCallback(response) { 
     console.log('Memcached... OK'); 
     $log.info(response); 

     //I wannt to move this section below. 
     $http({ 
      method: 'GET', 
      url: '/wsrp_crm/dictionary' 
     }).then(function successCallback(response) { 
      console.log('Dictionary... OK'); 
      $log.info(response); 
     }, function errorCallback(response) { 
      console.log('Dictionary... ERR'); 
     }); 

    }, function errorCallback(response) { 
     console.log('Error, can\'t resolve memcache'); 
     $log.info(response); 
    }); 
}; 

和目錄結構:

├───node_modules 
├───public 
│ ├───bin 
│ ├───css 
│ ├───fonts 
│ │ └───bootstrap 
│ ├───img 
│ └───js 
└───src 
    ├───app 
    │ ├───config 
    │ ├───controllers 
    │ └───services 
    ├───fonts 
    ├───js 
    ├───libs 
    │ ├───bootstrap-sass 
    │ ├───font-awesome 
    │ └───jquery 
    ├───partials 
    └───scss 
     ├───mixins 
     └───variables 

要清楚,我wannt將服務移動到dir:./s ervices/dictionary.service.js

回答

1

也許,這是一個解決方案:

dictionary.service.js

app.services('DictionaryServices', dictionaryServices) 
    app.$inject = ['$http', '$q'] 
    function dictionaryServices($http, $q) { 
    this.getDictionary = function() { 
     var deferred = $q.defer() 
     var url = '/api/url'; 

     $http.get(url) 
     .success(deferred.resolve) 
     .error(deferred.reject) 

     return deferred.promise 
    } 
} 

controller.js

注入DictionaryServices和呼叫到DictionaryServices.getDictionary():

app.controller('MyController', myController) 
myController.$inject = ['$scope', 'DictionaryServices'] 
function myController($scope, DictionaryServices) { 

    DictionaryServices.getDictionary().then(function(response) { 
    console.log(response) 
    }) 

} 
+4

不要爲此使用'$ q'。這是一種非常常見的反模式,因爲'$ http'已經返回一個承諾。也'成功'和'錯誤'已棄用 – charlietfl

+0

@charlietfl哦!這是真的! $ http返回承諾...謝謝!現在我必須改變我所有的服務..... :) – zamarrowski

+0

這是正確的,現在我正在改變所有$ http請求,這就是我重寫以前版本的原因。成功,不推薦使用,但仍然idk如何將此服務移動到單獨的文件。大多數解決方案都是有說服力的。 –

相關問題