gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:12:13 24 4
gpt4 key购买 nike

我对从 Controller 到单独文件的字典的单独 $http GET 请求有问题,作为服务。我试过查找这个,但我还没有找到 eglibe 提示。请支持。

文件如下:

应用程序.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

最佳答案

也许,这是一个解决方案:

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

注入(inject) DictionaryServices 并调用 DictionaryServices.getDictionary():

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

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

}

关于AngularJS 将 $http 服务放到单独的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38121622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com