为什么$ http服务会消耗完整的url服务而$ resource不会?

时间:2017-09-29 09:21:21

标签: angularjs ajax rest

这是我的服务:

app.factory("ResourceService", function ($resource, $q, $http) {
return {
    getAll: function () {
        var deferred = $q.defer();
        $http.get('https://dog.ceo/api/breeds/list/all').then(function (response) {
            deferred.resolve(response);
        }, function (error) {
            deferred.reject(error);
        });
        return deferred.promise;
    },
    allUsingResource: function () {
        return $resource('https://dog.ceo/api/breeds/list/all');
    }
}
});

这是我的控制者:

app.controller("Controller", function ($scope, ResourceService) {
function getAll() {
    ResourceService.getAll().then(function (response) {
        $scope.all = response.data;
    }, function (error) {
        console.log(error);
    });
}
function runAll() {
    var data = ResourceService.allUsingResource();
    data.query(function (response) {
        console.log(response);
    }, function (error) {
        console.log(error);
    });
}
runAll();
getAll();
});

虽然所有内容都以$ http的速度膨胀,但我使用$ resource获得了badcfg:

错误:[$ resource:badcfg] http://errors.angularjs.org/1.6.5/ $ resource / badcfg?p0 = query& p1 = array& p2 = object& p3 = GET& p4 = https%3A%2F%2Fdog.ceo%2Fapi %2Fbreeds%2Flist%2Fall

我错过了什么?

1 个答案:

答案 0 :(得分:0)

默认情况下,当您在data.query对象上运行$resource时,它需要array in response

 'query':  {method:'GET', isArray:true},

因此,请确保返回数组而不是https://dog.ceo/api/breeds/list/all

中的对象

从URL Angularjs中读取错误:

https://docs.angularjs.org/error/$resource/badcfg?p0=query&p1=array&p2=object&p3=GET&p4=https:%2F%2Fdog.ceo%2Fapi%2Fbreeds%2Flist%2Fall

  

操作query的资源配置出错。预期的响应包含一个数组但得到一个对象(请求:GET https://dog.ceo/api/breeds/list/all

     

描述

     

当$ resource服务期望响应可以作为数组反序列化但接收对象时,会发生此错误,反之亦然。默认情况下,所有资源操作都需要对象,但需要数组的查询除外。

     

要解决此错误,请确保您的$ resource配置与从服务器返回的数据的实际格式相匹配。

     

有关详细信息,请参阅$resource API参考文档。

相关问题