【问题标题】:Angular $http service wait until data returnedAngular $http服务等到数据返回
【发布时间】:2016-08-15 03:52:55
【问题描述】:

我创建了这个 http 服务:

(function () {
    "use strict";

    angular.module("inspectionReview").factory("inspectionReviewServices", ["$http", "config", inspectionReviewServices]);

    function inspectionReviewServices($http, config) {
        var serviceAddress = config.baseUrl + "api/InspectionReview/";
        var service = {
            getValues: getValues
        };
        return service;

        function getValues(objectId, frequencyId) {
            return $http.get(serviceAddress + "getValuesByObjectTypeId/" + objectId + "/" + frequencyId);
        }    
    }
})();

这里我在控制器中使用它来获取数据:

function checkInspection() {
    var frequencyId = 5;
    inspectionReviewServices.getValues($scope.object.Id, frequencyId).then(function (result) {
       $scope.someData = result.data;
    });
}

当我调用函数 checkInspection 时,我需要等到 $scope.someData 属性被数据填充,并且只有在它被数据填充之后才能执行更多行。目前我得到了进一步执行的承诺和代码。

编辑(根据达伦的回答):

我更改了调用服务的服务和函数:

function getValues2(objectId, frequencyId) {
    return $http.get(serviceAddress + "getValuesByObjectTypeId/" + objectId + "/" + frequencyId).then(function (result) {
        return result.data;
    });
}

这是在控制器中调用服务的函数:

    function checkInspectionReviewValidety() {
        var frequencyId = 5;
        return inspectionReviewServices.getValues2($scope.object.Id, frequencyId)
        }

但我仍然没有得到想要的结果。

如何更改 checkInspection 函数以使其等到 $scope.someData 属性被数据填充?

【问题讨论】:

  • 好吧,你不能。将需要result.data 的逻辑放在then 块中。
  • 你必须把你想做的工作作为一个函数传入。

标签: angularjs angularjs-http


【解决方案1】:

您可以在 $http 服务方法上使用.then

$http.get(serviceAddress + "getValuesByObjectTypeId/" + objectId + "/" + frequencyId).then(function() {
  // Populate items from callback 
});

【讨论】:

  • 所有要做的就是移动承诺解决的地方 - 它不会使其同步,因此 OP 将面临同样的问题。
  • 我对问题进行了一些修改。请问您现在可以看到了吗?
  • @DarrenDavies,正如 Lex 所指出的,这完全没有区别。
【解决方案2】:

你不能那样做。 promises 的整个方面是处理异步请求并在 promise 被解决/拒绝时执行。如果您希望在填充数据后执行某些代码,请将这部分代码移动到 .then 块中。

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 1970-01-01
    • 2017-02-21
    • 2019-10-31
    • 1970-01-01
    • 2017-08-03
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多