Problems with $Resource Angularjs

Asked

Viewed 151 times

1

I’m having a problem using $Resource from Angularjs. The data coming from the API is only displayed in the service but when I call in the controller the list is empty.

//service
angular.module('core.rota').
    factory('Rota', function ($resource,$cookies, $location, $httpParamSerializer,LoginRequiredInterceptor) {
        var url =  '/api/rota/:id/'

                //Carregamento dos locais
        var locaisQuery = {
            url:'/api/core/local/',
            method:"GET",
            params: {},
            isArray: true,
            cache:false,
            interceptor: {responseError: LoginRequiredInterceptor},
            transformResponse: function (data, headersGetter, status) {
               var finalData = angular.fromJson(data)
                console.log(finalData)// ok os dados são exibidos
               return finalData.results
            }
        }

        var token = $cookies.get("token")
        if (token){
            minhasRotasQuery["headers"] = {"Authorization": "JWT " + token}
            rotasQuery["headers"] = {"Authorization": "JWT " + token}
            locaisQuery["headers"] = {"Authorization": "JWT " + token}     
        }

        return $resource(url, {},{
            minhas:minhasRotasQuery,
            todas:rotasQuery,
            query:locaisQuery,
            get:getRota,
            create:createRota,
            createServ:createServico,
            // delete: commentDelete,
            update: updateRota,
        })
});

//component
angular.module('rotacreate').
        component('rotacreate',{
            templateUrl:'/api/templates/rotas/rotacreate.html',
            controller: function(Rota,User,$cookies, $http, $location, $routeParams, $scope,$filter,moment,LoginRequiredInterceptor){

            Rota.query(function(data){
                    console.log(data)//Array vazio Array[ ]
                    $scope.users = data
                },function (err_data) {
                    console.log(err_data)
                })
}

1 answer

0

Your current code is not running the method and awaiting resolution of Promise - actually is just passing objects to the method.

Altere of

Rota.query(function(data){ [...]

for

Rota.query().then(function(data){ [...]

or

Rota.query().$promise.then(function(data){ [...]

Depending on your version.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.