Filter AngularJS REST JSON Data: error:badcfg Resp

2019-08-07 05:50发布

问题:

I am trying to use a routeparam to filter the results from a REST call, but am not getting any results returned but rather receiving the following error:

Error: error:badcfg Response does not match configured parameter
Error in resource configuration for action `get`. Expected response to contain an object but got an array

The value I am attempting to get is by the articlecategoryid. If I drop my URL into a browser tool such as Postman it works. An example URL that returns as desired by articlecategoryid is as follows:

https://myrestcall.net/tables/articles/?$filter=(articlecategoryid eq 1)

However, using this in Angular does not seem to resolve and produces the error.

Here is some sample REST Data from this call:

[
{
    "id": "66D5069C-DC67-46FC-8A51-1F15A94216D4",
    "articletitle": "artilce1",
    "articlecategoryid": 1,
    "articlesummary": "article 1 summary. "
},
   {
    "id": "66D5069C-DC67-46FC-8A51-1F15A94216D5",
    "articletitle": "artilce2",
    "articlecategoryid": 1,
    "articlesummary": "article 2 summary. "
}, 
{
    "id": "66D5069C-DC67-46FC-8A51-1F15A94216D6",
    "articletitle": "artilce3",
    "articlecategoryid": 1,
    "articlesummary": "article 3 summary. "
},   
]

Here is my App setup:

var pfcModule = angular.module('pfcModule', [
'ngRoute',
'ui.bootstrap',
'auth0',
'angular-storage',
'angular-jwt',
'pfcServices',
'pfcControllers']);

pfcModule.config([
'$routeProvider',
'authProvider',
'$httpProvider',
'$locationProvider',
'jwtInterceptorProvider',
function ($routeProvider, authProvider, $httpProvider, $locationProvider, jwtInterceptorProvider) {
    $routeProvider.
        when('/home', { templateUrl: './views/home.html' }).
        when('/categories/:articlecategoryID', { templateUrl: './views/categories.html', controller: 'pfcCategoriesCtrl' }).
        when('/article/:articleID/:articleTitle', { templateUrl: './views/article.html', controller: 'pfcCtrl2' }).
        when('/add-article', { templateUrl: './views/add-article.html', controller: 'pfcPost', requiresLogin: true }).
        when('/login', { templateUrl: './views/login.html', controller: 'loginCtrl' }).
        otherwise({ redirectTo: '/home' });
    $httpProvider.defaults.headers.common['X-ZUMO-APPLICATION'] = 'myid';
    $httpProvider.defaults.headers.common['Content-Type'] = 'Application/json';
    authProvider.init({
        domain: 'mydomain',
        clientID: 'myid',
        callbackURL: location.href,
        loginUrl: '/login'
    });

    jwtInterceptorProvider.tokenGetter = function (store) {
        return store.get('token');
    }

    $httpProvider.interceptors.push('jwtInterceptor');
}])

.run(function ($rootScope, auth, store, jwtHelper, $location) {
$rootScope.$on('$locationChangeStart', function () {
    if (!auth.isAuthenticated) {
        var token = store.get('token');
        if (token) {
            if (!jwtHelper.isTokenExpired(token)) {
                auth.authenticate(store.get('profile'), token);
            } else {
                $location.path('/login');
            }
        }
    }

});
});

Here is my service:

     var pfcServices = angular.module('pfcServices', ['ngResource'])


pfcServices.factory('pfcArticleCategories', ['$resource', function ($resource) {
    return $resource('https://myrestcall.net/tables/articles/?$filter=(articlecategoryid eq :articlecategoryID)', { articlecategoryID: '@articlecategoryid' },
    {
        'update': { method: 'PATCH' }
    }
    );
}]);

Here is my controller:

 var pfcControllers = angular.module('pfcControllers', ['auth0']);

pfcControllers.controller('pfcCategoriesCtrl', ['$scope', '$routeParams', 'pfcArticleCategories', function ($scope, $routeParams, pfcArticleCategories) {
    $scope.category = pfcArticleCategories.get({ articlecategoryID: $routeParams.articlecategoryID });
}]);

Here is the page that would output the REST data (categories.html):

div class="row">
<div class="col-md-4">
    <h2>Heading</h2>
    Sort By: <select ng-model="articleSortOrder">
        <option value="+id">ID</option>
        <option value="+articletitle">Article Title</option>
        <option value="+articlecategoryid">Article Category</option>
    </select>
    <table class="table table-striped">
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Category ID</th>
        </tr>
        <tr ng-repeat="articles in category | orderBy:articleSortOrder">
            <td>{{articles.id}}</td>
            <td>{{articles.articletitle}}</td>
            <td>{{articles.articlecategoryid}}</td>
        </tr>
    </table>
</div>

Here is how I link into this page to filter it by the routeparam (home.html):

<a href="#categories/1">Article 1 Category</a>
<a href="#categories/2">Article 2 Category</a>

UPDATE: My other REST calls are working, even with a routeparam such as https://myrestcall.net/tables/articles/:articleID so I am focusing on the ?$filter= aspect of the failing call. Have others had issues with passing values into a REST call, as the variable is not directly after a / as it is in /:articleID

回答1:

In your pfcServices factory definition add isArray:true to 'update': { method: 'PATCH' }, every time you get a JSON array as a result you need to add isArray: true to method definition.

  var pfcServices = angular.module('pfcServices', ['ngResource'])
pfcServices.factory('pfcArticleCategories', ['$resource', function ($resource) {
        return $resource('https://myrestcall.net/tables/articles/?$filter=(articlecategoryid eq :articlecategoryID)', { articlecategoryID: '@articlecategoryid' },
        {
            'update': { method: 'PATCH', isArray:true }
        }
        );
    }]);

isArray – {boolean=} – If true then the returned object for this action is an array, see returns section.

See docs here



回答2:

Solved it! The issue is in the controller as I was using a 'Get'. A 'Get' works fine for retrieving something by the id (ex. https://myrestcall.net/tables/articles/:articleID).

However, I needed to use the 'query' command as this has an implicit isArray:true (please see the Angular Resource Doc where it states 'query': {method:'GET', isArray:true},)

When I changed my controller from:

 pfcControllers.controller('pfcCategoriesCtrl', ['$scope', '$routeParams', 'pfcArticleCategories', function ($scope, $routeParams, pfcArticleCategories) {
$scope.category = pfcArticleCategories.get({ articlecategoryID: $routeParams.articlecategoryID });
}]);

To:

pfcControllers.controller('pfcCategoriesCtrl', ['$scope', '$routeParams', 'pfcArticleCategories', function ($scope, $routeParams, pfcArticleCategories) {
$scope.category = pfcArticleCategories.query({ articlecategoryID: $routeParams.articlecategoryID });
}]);

It resolves as desired.