我正在构建一个基本应用程序来加载当前正在进行的事件列表。我有一个基本的 CRUD 系统,我在 Controller 中构建了所有功能。建议我使用 Angular 自定义服务,而不是在 Controller 上堆砌许多功能。
我现在正在将我的代码重新编写为自定义服务,但无法完全掌握其结构。下面是我到目前为止所得到的,但目前我在这一行的服务代码上收到错误 Unexpected token .
varconfiguration.data_result_1 =configurations.data_result_1.split("\r\n");
我感觉我的代码全错了,但在网上找不到类似的情况作为自己的依据。希望得到一些帮助。这是我到目前为止所得到的:
服务:
var GDI_configurations = {};
app.service('MyService', function () {
this.sayHello() //fetch data on page load.
this.sayHello = function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'AJAX PATH',
headers: { "Accept": "application/json;odata=verbose;charset=utf-8"}
}).then(function(data){
var configurations = data;
var configurations.data_result_1 = configurations.data_result_1.split("\r\n");
var configurations.data_result_2 = configurations.data_result_2.split("\r\n");
};
});
Controller :
app.controller('AppController', function (MyService, $scope) {
$scope.configurations = function() { MyService.sayHello() };
});
最佳答案
首先,您没有在服务中注入(inject) $q 和 $http 。 其次,您没有使用 $q 来解决或拒绝。 第三,从 $q 创建一个 Promise 是多余的,因为 $http 服务返回一个 Promise。
请考虑以下代码:
app.service('MyService', function ($http) {
this.sayHello = function () {
return $http({
method: 'GET',
url: 'AJAX PATH',
headers: { "Accept": "application/json;odata=verbose;charset=utf-8"}
});
};
});
app.controller('AppController', function (MyService, $scope) {
$scope.configurations = null;
MyService.sayHello().then(function(data){
$scope.configuration = data;
$scope.configurations.data_result_1 = $scope.configurations.data_result_1.split("\r\n");
$scope.configurations.data_result_2 = $scope.configurations.data_result_2.split("\r\n");
}, function(error){
// some error occurred
})
});
如果您想在服务内缓存响应以从多个 Controller 检索它,请告诉我..我可以以这种方式重写代码..希望这对您有帮助..干杯
关于javascript - Angular - 无法获取服务以获取成功的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41642200/