【问题标题】:ngResource.myfunc().$promise.then returns empty arrayngResource.myfunc().$promise.then 返回空数组
【发布时间】:2016-06-21 11:08:33
【问题描述】:

我正在使用 angularjs-1.5.0 来编写我的应用程序。

我创建了一个使用 $resource 从 api 服务器获取数据的服务。该服务称为 MyApi。

(function () {

angular.module('myalcoholist').factory('MyApi', ['$resource', '$auth', function ($resource, $auth) {
    return $resource('https://myalcoholist.com:8888/drink/:cmd',
        null, {
                 pouringSpeedTypes: {
                method: 'GET',
                params: {api_token: $auth.getToken(), cmd: 'get_pouring_speed_types'},
                isArray: true
            },
            pouringLocationTypes: {
                method: 'GET',
                params: {api_token: $auth.getToken(), cmd: 'get_pouring_location_types'},
                isArray: true
            }
        });
        });
}]);

})();

在我的控制器中,我使用以下代码使用此服务:

 MyApi.pouringLocationTypes().$promise.then(function(data) {
        console.info(data);
    });
    MyApi.pouringSpeedTypes().$promise.then(function (data) {
        console.info(data);
    });

问题是数据是.. 我猜是一个承诺。 这是数据包含的内容:

$promise: d
$resolved: true
length: 0
__proto__: Array[0]

我该怎么办?如何从 get 请求中获取实际数据?

【问题讨论】:

  • 也许试试 MyApi.pouringLocationTypes().then(function(data){ ... //do something with data }) 这应该会给你从 API 调用返回的任何东西,让你做任何事情
  • @HolyMoly 我正要写这个,但有时这里呈现的方式会让你怀疑他们现在的方式是否是 correct 方式。
  • 然后在我尝试的时候没有定义
  • 您的代码看起来正确。这是授权问题或服务器问题。检查您的网络选项卡以查看服务器返回的内容。
  • 那么MyApi.pouringLocationTypes() 会返回什么?

标签: javascript angularjs promise angular-resource ngresource


【解决方案1】:

感谢您的 cmets,您允许我查明问题。

首先,我没有更新我的服务器代码,这就是为什么当您尝试这些地址时,您会得到 Method not Allowed。

我遇到的问题是这些请求确实返回了空数组。

首先我的 API 返回一个 json 对象而不是数组,所以我将 isArray 更改为 false。

所以在那之后并实际修复了我的 API 服务器,这就是我收到的:

$promise: d
$resolved: true
data: Array[4]
success: true

我的 API 服务器返回一个带有数据和成功的 json。所以现在一切正常!非常感谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2021-04-21
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2021-08-11
    • 2017-02-27
    相关资源
    最近更新 更多