javascript - 如何从 Angular js中的服务返回值?

标签 javascript angularjs

我知道数据来自服务器(我进行了单元测试,并且在 Chrome 的调试器中看到了数据),但我不知道如何将数据从 Angular 服务返回到 Angular Controller 。

服务:

已更新

surchargeIndex.service('customerService', [
'$http', function ($http) {
    this.getTest = function () {
       return $http({
                method: "GET",
                url: "api/Customer/GetTest",
            })
            .success(function(data) {
                return data;
            });
    };
}

]);

Controller :

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) {
    $scope.customers = customerService.getTest();

});

Data 具有来自服务器的数组,因此该数组会填充到服务中。所以重申一下数据是存在的;但是,我在调试期间在成功处理程序内部收到 404 错误。

我错过了什么?

最佳答案

$http 异步工作;幸运的是,它返回一个 promise ,当从服务器检索到响应时,该 promise 将得到履行。所以你应该返回$http的get方法并使用返回的promise来处理数据。

this.getTest = function () {
        return $http({
                method: "GET",
                url: "api/Customer/GetTest",
            })
            .success(function(data) {
                return data;
            })
            .error(function() {
                alert("failed");
        }); // This returns a promise

    };

然后在您的 Controller 中,您应该使用该 promise 来检索预期的数据。

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) {
    //Use the returned promise to handle data, first parameter of the promise is used for successful result, if error happens, second parameter of the promise returns the error and you can do your error handling in that function
    customerService.getTest().then(function(customers){$scope.customers = customers;},   function(err){console.error(err);})
});

关于javascript - 如何从 Angular js中的服务返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27297102/

相关文章:

javascript - AngularJs 2 - 其他组件模板不可用的主构造器变量

javascript - anchor 标签的正确用法是什么?

javascript - 如何使用 jquery 删除没有 img 标签的元素类?

javascript - jQuery $ ("#radioButton").change(...) 在取消选择期间未触发

javascript - 在 HTML 中记住用户区域设置选择的最简单方法

javascript - 将侧边栏中的内容垂直对齐到文本中的引用 [基于 Tufte 风格的评论]

AngularJS promise 在完成时不会调用 `then` 回调

javascript - 如何在 JavaScript 中访问 Angularjs $scope?

javascript - 如何将 Controller 的范围属性传递给自定义指令?

javascript - slice() 在控制台中正确返回,但字符串在 <td> 中未被替换