J86
J86

Reputation: 15307

Accessing returned data from service in the controller in AngularJS

I am working in a project that has AngularJS front-end and ASP.NET Web API back-end.

I have a service that calls the web API and returns a bunch of JSON data. I am trying to access that data in my controller, but I get an error saying the property I'm after is undefined! The property I'm after is the RegisteredKeeperName.

$scope.getCrateDetails = function (result, isInsert) {
    $scope.showCrateDetails = true;
    getCrateDetails();

    if (!$scope.premiumCrate.RegisteredKeeperName.toLowerCase().indexOf("Green Farm") > -1) {
        $scope.calloutClass = 'callout-danger';
        $scope.calloutMessage = 'We (Green Farm) cannot provide this service with the necessary documents.';
    } else {
        $scope.calloutMessage = 'All is good!';
    }
};

Even though when I print out the $scope I can see the property I'm after is populated with the correct information!

{{premiumCrate.RegisteredKeeperName}}

My service code like so:

function getCrateDetails() {
    // service call goes here.
    stockData.GetCrateDetails($scope.premiumCrate.Id).then(
        function (cData) {
            $scope.premiumCrate = cData;
        },
        function () {

        });
};

Upvotes: 0

Views: 79

Answers (1)

tymeJV
tymeJV

Reputation: 104795

getCreateDetails is an async call (you're trying to use the data before it has been returned and assigned), you should return that call using .then and access it in the controller, like so:

function getCrateDetails() {
    return stockData.GetCrateDetails($scope.premiumCrate.Id).then(function (cData) {
        return cData.data;
    }, function () {

    });
};

And make the call:

getCrateDetails().then(function(data) {
    console.log(data); //hey data!
    $scope.premiumCrate = data;

    if (!$scope.premiumCrate.RegisteredKeeperName.toLowerCase().indexOf("Green Farm") > -1) {
        $scope.calloutClass = 'callout-danger';
        $scope.calloutMessage = 'We (Green Farm) cannot provide this service with the necessary documents.';
    } else {
        $scope.calloutMessage = 'All is good!';
    }
});

Upvotes: 1

Related Questions