简体   繁体   中英

AngularJS - Reading JSON from Factory, using result

new to Angular and stuck on something that should be pretty easy...

I have a few resources:

.factory( 'RSVPRes', function ( $resource )  {
  return {
    RSVP: $resource("../reservations/:id.json", {id:'@id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
    Meals: $resource('../meals.json'),
    UserInvites: $resource('../userinvite.json')
  };
})

Meals.json:

[{"id":1,"name":"Chicken","description":"Chicken Yum!","created_at":"2013-12-11T22:37:28.994Z","updated_at":"2013-12-11T22:37:28.994Z","event_id":1,"event":{"name":"Wedding"}},{"id":2,"name":"Steak","description":"9oz","created_at":"2013-12-11T22:37:29.004Z","updated_at":"2013-12-11T22:37:29.004Z","event_id":2,"event":{"name":"Rehersal"}},{"id":3,"name":"Veggie","description":"Vegan","created_at":"2013-12-11T22:37:29.008Z","updated_at":"2013-12-11T22:37:29.008Z","event_id":3,"event":{"name":"Stag"}}]

UserInvites.json:

[{"id":18,"created_at":"2013-12-11T23:00:18.684Z","updated_at":"2013-12-11T23:00:18.684Z","event_id":1,"registry_id":1,"user_id":9,"total_in_party":2}]

Data seems to be formatted the same. All good here.

EDITED Now in my controller

.controller('RSVPCtrl', function RSVPController($scope, RSVPRes, $state, $stateParams) {

  //GET INVITATION(S)
  RSVPRes.UserInvites.query().$promise.then(function(response){
    $scope.invitation = response.data;
    //BUILD SELECT LIST FOR MEALS
    $scope.meals = RSVPRes.Meals.query();

    //EDIT
    if ($scope.rsvpId) {
      $scope.rsvp = RSVPRes.RSVP.get({id: $scope.rsvpId}, function() {
        // $scope.selectedUser = $scope.invite.user_id;
        // $scope.selectedEvent = $scope.invite.event_id;
        // $scope.selectedRegistry = $scope.invite.registry_id;
        // $scope.selectedTotalInParty =  $scope.invite.total_in_party;
      });
    }
    //NEW 
    else {
      //INITIALIZE EMPTY GUESTS
      $scope.guests = [];
      for (var i = 0; i < $scope.invitation.total_in_party; i++) {
        $scope.guests[i] = {
          first_name: '',
          last_name: '',
          meal: 1,
          rsvp: 0
        };
      }
    }
  });

  $scope.submit = function() {
    for (var i = 0; i < $scope.guests.length; i++){
       $scope.rsvp = new RSVPRes.RSVP();
       $scope.rsvp.first_name = $scope.guests[i].first_name;
       $scope.rsvp.last_name = $scope.guests[i].last_name;
       $scope.rsvp.meal_id = $scope.guests[i].meal;
       $scope.rsvp.rsvp = $scope.guests[i].rsvp;
       $scope.rsvp.$save();
    }
    $state.transitionTo('rsvps');
  };
})

Inspecting my response.data I get my information, however my $scope.invitation is still undefined...

Any help is much appreciated!

Looks like your response.data will be an array, which means that [$scope.invitation] is better named [$scope.invitations], as you're set up to get (possibly) more than one. And that multiple invitations possibility suggests that the For loop you set up to build empty guest objects is not quite right. Maybe try this...

for (var i = 0; i < $scope.invitation.length; i++){
    $scope.guests[i] = [];
    for (var j=0; j < $scope.guests[i].total_in_party; j++) {
        $scope.guests[i].total_in_party[j] = {
            first_name: '',
            last_name: '',
            meal: 1,
            rsvp: 0
        };
      }
    }
}

I think you are confusing the reponse in the callback for a $resource with the response for an $http GET call. You should use only response in the callback for the resource instead of resource.data . Like this:

  //GET INVITATION(S)
  RSVPRes.UserInvites.query().$promise.then(function(response){
    $scope.invitation = response;
    //BUILD SELECT LIST FOR MEALS
    $scope.meals = RSVPRes.Meals.query();

    //EDIT
    if ($scope.rsvpId) {
      /* $scope.rsvp = RSVPRes.RSVP.get({id: $scope.rsvpId}, function() {
        // $scope.selectedUser = $scope.invite.user_id;
        // $scope.selectedEvent = $scope.invite.event_id;
        // $scope.selectedRegistry = $scope.invite.registry_id;
        // $scope.selectedTotalInParty =  $scope.invite.total_in_party;
      });*/ 
    }
    //NEW 
    else {
      //INITIALIZE EMPTY GUESTS
      $scope.guests = [];
      for (var i = 0; i < $scope.invitation.total_in_party; i++) {
        $scope.guests[i] = {
          first_name: '',
          last_name: '',
          meal: 1,
          rsvp: 0
        };
      }
    }
  });

From the docs :

$promise: the promise of the original server interaction that created this instance or collection.

On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

On failure, the promise is resolved with the http response object, without the resource property.

Hence, in case of success , the response of a resource is different from a $http call.

Working example: http://plnkr.co/edit/k7rMLJmQpbwWJMcfqcvl?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM