Wait till response comes back from service in angularjs

1.41K viewsProgrammingangularjs javascript programming
0

How to retrieve response data from Angular $http request? How do we make sure that we wait until response returns from $http service

Answered question
0

"use strict";
var app = angular.module("App", []);
var baseURL = 'http://xyz.com/TeamData?teamId=',
    teamIds = {
        'IT': 'abcrrr233',
        'Finance': 'jlfgfd244'
    };
app.controller("AppCtrl", function($scope, $filter, $http, $q) {
    var url = baseURL + teamIds['Accounts'];
    $scope.teamMembers = []; // initialize variables
    $scope.teamTitle = "";
    $scope.getTeamInfo = function(method, url, _data) {
        var promise = $http({
            method: method,
            url: url,
            data: _data,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).
        success(function(data, status, headers, config) {
            if (data.title.length > 0) { // check for NULL (zero length response)
                return data;
            } else {
                console.log(data)
                return -1; //error
            }
        }).
        error(function(data, status, headers, config) {
            return -1; // error
        });
        return promise;
    }
    var promise = $scope.getTeamInfo('GET', url, '');
    //resolve the promise returned by the getTeamInfo() function
    promise.then(function(response) {
        $scope.teamTitle = response.data.title;
        $scope.teamMembers = response.data.teamMembers;
        console.log($scope.teamMembers);
    });
    // dropdown select change event
    $scope.changeTeam = function() {
        var promise = $scope.getTeamInfo('GET', baseURL + teamIds[$scope.teamValue], '');
        //resolve the promise returned by the getTeamInfo() function
        promise.then(function(response) {
            $scope.teamTitle = response.data.title;
            $scope.teamMembers = response.data.teamMembers;
            console.log($scope.teamMembers);
        });
    }
});

Answered question
Write your answer.

Categories