AngularJS 使用 $resource 服务.GET 请求未解决承诺 [英] AngularJS using $resource service. Promise is not resolved by GET request

查看:26
本文介绍了AngularJS 使用 $resource 服务.GET 请求未解决承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有这样的服务:

   services.factory('User', function($resource){
        return $resource('/rest/usersettings/:username', {}, {
            get:    {method: 'GET'},
            update: {method: 'POST'}
        });
    });

所以它应该像这样使用:

So it is supposed to be used like this:

        scope.user = User.get( {username: 'bob'}  );    // GET

        console.log( JSON.stringify(scope.user) )       // {"$promise":{},"$resolved":false} 

所以,当我发送 GET 请求时,一切正常,构建这个 ur + params:

So, when I send GET request, it goes OK, building this ur + params:

http://localhost:9000/rest/usersettings/bob

问题,为什么我有: {"$promise":{},"$resolved":false}

如果我的 GET 请求导致从服务器返回 json 响应:{"username":"bob","email":"bob@bobs.com"} 那么我期待让我的 scope.user 填充数据.

If my GET request leads to json-response back from the server:{"username":"bob","email":"bob@bobs.com"} then I'm expecting to have my scope.user filled by data.

我应该等待承诺准备好/解决了吗?

Should I wait somehow promise is ready / resolved ?

推荐答案

User.get( {username: 'bob'} ) 不会立即返回您的实际数据.当ajax返回时,它会返回一些东西来保存你的数据.在那($promise)上,您可以注册一个额外的回调来记录您的数据.

User.get( {username: 'bob'} ) does not return your actual data immediately. It returns something will hold your data when the ajax returns. On that (the $promise), you can register an additional callback to log your data.

您可以将代码更改为:

   scope.user = User.get( {username: 'bob'}  );    // GET
   scope.user.$promise.then(function(data) {
       console.log(data);
   });

这篇关于AngularJS 使用 $resource 服务.GET 请求未解决承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆