Search code examples
javascriptangularjsundefinedfactoryngresource

AngularJS - How can I use the data retrieved using a Factory GET request in my controller?


I created an Angular factory for fetching JSON data. I'm using $resource with the get method to retrieve this JSON object from the server. The object itself contains child objects.

I've been trying to use the data I retrieved with this factory in my controller but when I call the $scope variable, I get some variation of this

Cannot read property propertyName of undefined.

I could read the property when I logged it to the console so I don't get why it just disappears. To diagnose it, I tried passing by reference another variable.

The problem is that I can find the object and its keys by logging the console. The problem is that when I try to use this data, the object keys become undefined. I have no idea why this happens.

 NewOrder.get({"id": $stateParams.loopId, "orderId": $stateParams.orderId}).$promise.then(function(order) {
    $scope.myData = order["data"];
    console.log("this is an order", order);
});

Here is my factory

angular.module('myApp')
    .factory('NewOrder', function($resource) {
        return $resource('/api/loops/:id/orders/:orderId');
    });

I found out that if I create a new variable and set it equal to the value of myData, the object inside my key disappears.

This works

$scope.getOrder = function() {
    console.log($scope.myData);
}
=> Object {recruitingLeague: "NAHL", playerPosition: "LeftDefense", playerDOB: Object, playerHeight: Object, playerWeight: Object…}

Creating a new variable and passing by reference the value of the previous variable (for diagnosis purposes) doesn't.

$scope.newData = $scope.myData;

$scope.getOrder = function() {
    console.log($scope.newData);
}
=> undefined

I cannot understand why the objects I'm retrieving from my server suddenly disappear.


Solution

  • The service is asynchronous, so $scope.myData isn't there when

    $scope.newData = $scope.myData;
    

    occurs, but it is already there when

    $scope.getOrder = function() {
        console.log($scope.myData);
    }
    

    is called.