angularjs http服务等待数据

标签 angularjs

我有 HTTP 服务返回对 inspection2update.DamageTypeId 属性的 promise 并继续进一步执行。

HTTP 服务:

function post(objectTypeId, damageDescription) {
    var defer = $q.defer();
    $http.post(serviceAddress + "save/" + objectTypeId + "/" + damageDescription).then(function (response) {
        defer.resolve(response.data);
    });
    return defer.promise;
}

这里是我在 Controller 中调用服务的方式:

inspection2update.DamageTypeId = damageTypesService.save(inspection2update.ObjectTypeId, self.dType);

但我需要等到我从服务中获取数据,然后才能进一步执行。

为此,我在 $http 解析器中使用了 $q 服务,但我仍然从我的服务中得到了 promise ,但没有数据。

我必须在我的代码中更改什么才能让服务等待数据?

最佳答案

您正在返回一个在 http 调用完成获取数据后解析的 promise 。使用此服务的消费者需要等待 promise 解析,然后然后对数据做一些事情。

使用then语法接收promise数据并进一步执行:

damageTypesService.save(inspection2update.ObjectTypeId, self.dType).then(function(data) {
    inspection2update.DamageTypeId = data;
    // rest of execution...
});

P.S - 据我所知,在你的情况下没有使用 $q (除非你想与数据混合/制作日志等......)。您可以按原样返回 $http 调用:

function save(objectTypeId, damageDescription) {
    return $http.post(serviceAddress + "save/" + objectTypeId + "/" + damageDescription);
}

关于angularjs http服务等待数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38846613/

相关文章:

angularjs - Redactor所见即所得在AngularJs指令中的集成

AngularJS:如何提供搜索工具并导致传递参数的路由更改?

angularjs - User.Identity.GetUserId() 和 RequestContext.Principal.Identity.GetUserId() 在 WEB API Controller 中返回 NULL。使用基于 token 的身份验证

java - 使用 AngularJS 将 URL 中的 RequestParams 传递到 Spring MVC 后端

angularjs - Angular-基于$ stateParams更改路线状态更改的CSS类

javascript - ng-include 不包含局部 View

angularjs - 在 Phonegap 中使用 Angular UI-Router

javascript - 带有 typescript 的 Angular-js - 数据应该存储在 Controller 还是服务中?

ajax - Protractor - 在 $http 调用后选择中继器中的元素

angularjs - 如何在angularjs e2e Protractor 测试中上传文件