【问题标题】:AngularJS resolving $http promise too lateAngularJS 解决 $http 承诺为时已晚
【发布时间】:2015-07-16 06:51:06
【问题描述】:

我编写了一个 AngularJS 工厂,profileService,它处理设置/获取用户配置文件信息。它的getProfile 方法调用我的Web API,返回一个带有用户数据的JSON 对象,并用该数据解析$http.get 承诺。这个特殊的承诺被用在一个 login 方法中,它是一个身份验证工厂的成员。 login 中的代码块正在返回它自己的 $http.post 承诺(它正在请求一个令牌)。这个想法是在登录时检索和本地缓存用户的个人资料数据。

问题是$http.get 承诺解决得太晚了。也就是说,在我的控制台输出中,调用显示为解析为空 (undefined),紧随其后的是 getProfile 的内联输出,显示成功的配置文件对象检索。调用存储已解决承诺的变量也会产生undefined

根据我的研究,我倾向于这个问题是我没有正确考虑承诺。非常感谢任何有助于理解我出错的地方!

代码:profileService.getProfile(userName):

profileService.getProfile = function(userName) {
    return $http.get(ntSettings.apiServiceBaseUri + '/api/Profile/GetProfile?userName=' + userName)
        .then(function(response) {
            return response.data;
        });
};

代码:authService.login() 调用 getProfile

var profileService = $injector.get('profileService');
var userProfile = {};

profileService.getProfile(loginData.userName)
    .then(function(response) {
        userProfile = response;
        console.debug("authSvc -> login -> getProfile: Got profile data:", response.userProfile);
    }, function(error) {
        console.error("authSvc -> login: Unable to fetch profile", error);
    });
console.debug("authSvc -> login: Displaying profile object", response.userProfile);

控制台调试输出显示问题

authSvc -> login: Showing profile object: undefined
authSvc -> login -> getProfile: Got profile data: Object {FirstName: "John", LastName: "Doe", Birthday: "2015-05-06T04:00:00", Gender: 0, Location: "New York, NY"}

【问题讨论】:

  • This question 可能会帮助您了解 Promise 的工作原理
  • 你有一个类型错误,这应该是 userProfile = res 和 res.userProfile
  • @Julien 谢谢,我会审核的。
  • @JsIsAwesome 哎呀!这个错误只是我手动编辑该行以反映我在提交问题之前所做的最后一分钟代码更改。该代码实际上类似于您的建议。

标签: javascript angularjs angularjs-service angular-promise


【解决方案1】:

您需要将处理结果的逻辑放在 .then() 块中,“显示配置文件对象”日志记录在应用程序的 http-request-response 部分之外。 您可以将其视为一个独立运行的不同执行线程,并且不能假设“之前”的保证。

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    相关资源
    最近更新 更多