无法从 Angular $resource 获得响应

Can't get response from Angular $resource

我有一个工厂:

.factory('CompanyRolesResource', function($resource, FdConfig) {
    return $resource(FdConfig.routes.companyRoles);
})

我有一个使用这个工厂的函数:

ctrl.saveCompanyRole = function(companyRole) {
    return CompanyRolesResource.save({}, companyRole).$promise.then(function (response) {
            console.log(response)
        });
    };

在 Chrome DevTools 中,我看到响应是类似 {status: 200, data: {...}} 的数据。但是在 console.log 我只看到:

Resource
$promise: Promise
$$state: Object
__proto__: Object
$resolved: true

我的 data 在哪里?我在 $promise$$state.

中也找不到它

更新:

当我使用这种方式时,我得到了正确的回应:

   $http({
        url: FdConfig.routes.companyRoles,
        method: "POST",
        data: companyRole
    }).then(function (response) {
        console.log(response.data);
    });

但是我的 console.log(response) 在工厂里 returns undefined.

您无法直接从 $resource 访问您的数据,因为它是从服务器异步检索的。这意味着当您尝试访问数据时,您的数据尚未加载。您需要做的是为 $resource 操作提供回调。

Angular 1.2 开始,$resource 为每个操作提供 $promise,您可以在加载数据时使用这些操作检索数据:

CompanyRolesResource.save({}, companyRole).$promise.then(function (response) {
    // do whatever you want with your response.data here
});

Resource 是您的数据对象。当您使用 $resource 时,您不会得到作为 (status, data, headers, config) 对象的响应。您将直接得到响应(您的预期响应数据)

重要的是要意识到立即调用 $resource 对象方法 returns 一个空引用(对象或数组取决于 isArray)。从服务器返回数据后,现有引用将填充实际数据。

在后台,ngResource API 使用 angular.copy 将服务器数据复制到空引用。 如果数据不是 JavaScript 对象,则不会复制任何内容。

.save操作方法的情况下,如果返回数组,将抛出$resource:badcfg错误。

Error: $resource:badcfg

Response does not match configured parameter

Description

This error occurs when the $resource service expects a response that can be deserialized as an array but receives an object, or vice versa. By default, all resource actions expect objects, except query which expects arrays.

To resolve this error, make sure your $resource configuration matches the actual format of the data returned from the server.

For more information, see the $resource API reference documentation.

— AngularJS $resource:badcfg Error Reference