8

Ho un'applicazione RESTful con Laravel 4 e Angular JS.

Nel mio controller laravel,

public function index() { 

    $careers = Career::paginate($limit = 10); 

    return Response::json(array(
    'status' => 'success', 
    'message' => 'Careers successfully loaded!', 
    'careers' => $careers->toArray()), 
    200 
); 
} 

e lo script angolare,

var app = angular.module('myApp', ['ngResource']); 

app.factory('Data', function(){ 
    return { 
     root_path: "<?php echo Request::root(); ?>/" 
    }; 
}); 

app.factory('Career', [ '$resource', 'Data', function($resource, Data) { 
    return $resource(Data.root_path + 'api/v1/careers/:id', { id: '@id'}); 
}]); 

function CareerCtrl($scope, $http, Data, Career) { 

    $scope.init = function() { 
     $scope.careers = Career.query(); 
    }; 
} 

Eccomi po 'confuso per gestire i dati di risposta da assegnare alla variabile campo di applicazione, ora sto ottenendo array vuoto [] in $scope.careers. E anche Come posso gestire il successo e l'errore di mostrare alcuni messaggi come il seguente normale $http service,

$scope.init = function() { 

    Data.showLoading(); // loading progress 
    $http({method: 'GET', url: Data.root_path + 'api/v1/careers'}). 
    success(function(data, status, headers, config) { 
     Data.hideLoading(); 
     $scope.careers = data.careers.data; 
    }). 
    error(function(data, status, headers, config) { 

     if(data.error.hasOwnProperty('message')) { 
      errorNotification(data.error.message); 
     } else { 
      errorNotification(); 
     } 

     $scope.careers = []; 
    }); 
}; 

Vedi la mia richiesta in console utilizzando $ risorsa.

enter image description here

risposta

15

vita Prova questo:

app.factory('Career', [ '$resource', 'Data', function($resource, Data) { 
    return $resource(Data.root_path + 'api/v1/careers/:id', { id: '@id'}, { 
    query: { 
     isArray: false, 
     method: 'GET' 
    } 
    }); 
}]); 


Career.query(function(res) { 
    $scope.careers = res.careers.data; 
}, function(error) { 
    // Error handler code 
}); 
+0

Grazie, hai salvato il mio tempo ... – devo

+0

stesso qui a lottare per ore – Awena

2

See:. http://docs.angularjs.org/api/ngResource $ risorsa

$scope.init = function() { 
    var success = function(careerList, getResponseHeaders){ 
     $scope.careers = careerList; 
    }; 
    var failure = function(data){ 
     // TODO 
    }; 
    Career.query(success, failure); 
}; 

A causa di questo stranezze e altri disturbi Vorrei suggerire di usare Restangular al posto del default $ risorsa. Rende molto più facile

+0

La mia prima domanda, perché sto ottenendo array vuoto [] a $ scope.careers? – devo

+0

Non sicuro, potrebbe essere l'impostazione predefinita quando si verifica l'errore ... – fabrizioM

+0

Non è un fallimento. Vedi lo screenshot, sto ricevendo tutti i valori, come posso mapparlo alla variabile scope? – devo

Problemi correlati