Michael
Michael

Reputation: 13616

Angular $http service wait until data returned

I created this http service:

(function () {
    "use strict";

    angular.module("inspectionReview").factory("inspectionReviewServices", ["$http", "config", inspectionReviewServices]);

    function inspectionReviewServices($http, config) {
        var serviceAddress = config.baseUrl + "api/InspectionReview/";
        var service = {
            getValues: getValues
        };
        return service;

        function getValues(objectId, frequencyId) {
            return $http.get(serviceAddress + "getValuesByObjectTypeId/" + objectId + "/" + frequencyId);
        }    
    }
})();

And here I use it in controller to get data:

function checkInspection() {
    var frequencyId = 5;
    inspectionReviewServices.getValues($scope.object.Id, frequencyId).then(function (result) {
       $scope.someData = result.data;
    });
}

When I call function checkInspection I need to wait until $scope.someData property is populated by data and only after it populated by data only then further rows can be executed.Currently I get promise and code executed further.

EDIT(according to the Darren's answer):

I changed my service and function that calls service:

function getValues2(objectId, frequencyId) {
    return $http.get(serviceAddress + "getValuesByObjectTypeId/" + objectId + "/" + frequencyId).then(function (result) {
        return result.data;
    });
}

and here is function that calls for service in controller:

    function checkInspectionReviewValidety() {
        var frequencyId = 5;
        return inspectionReviewServices.getValues2($scope.object.Id, frequencyId)
        }

But still I dont get desired result.

How can I change checkInspection function to make it wait until $scope.someData property is populated by data?

Upvotes: 1

Views: 837

Answers (2)

Jayesh
Jayesh

Reputation: 110

You can't do that. The whole aspect of promises is to handle the async request and execute when the promise is resolved/rejected. If you want some piece of code to execute after data is filled up please move that part of the code into .then block.

Upvotes: 1

Darren
Darren

Reputation: 70728

You can use .then on the $http service method

$http.get(serviceAddress + "getValuesByObjectTypeId/" + objectId + "/" + frequencyId).then(function() {
  // Populate items from callback 
});

Upvotes: 1

Related Questions