AngularJS将$ http服务放入单独的文件中

时间:2016-06-30 11:19:46

标签: angularjs

我对从控制器到单独文件的单独$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

要清楚,我想把服务转移到目录:./ services / dictionary.service.js

1 个答案:

答案 0 :(得分: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)
  })

}