shreya gupta
shreya gupta

Reputation: 141

how to call two apis in one typeahead selection

I am using the angular typeahead:-

<label>USER</label>
     <input type="text" name="user" ng-model="a.user" autocomplete="off" typeahead="a for a in getAllUsers($viewValue);getAllStaffs($viewValue)" typeahead-loading="loadingCodes" typeahead-no-results="noResults">

My directive Code:-

scope.getAllUsers = function(key) {
    var obj = {
        "key": key
    }
    if (key.length >= 2) {
        return ApiServices.getAllUsers(obj).then(function(response) {
            return response.data.map(function(item) {
                return item;
            });
        });
    } else {
        return false;
    }
};

scope.getAllStaffs = function(key) {
    var obj = {
        "key": key
    }
    if (key.length >= 2) {
        return ApiServices.getAllStaffs(obj).then(function(response) {
            return response.data.map(function(item) {
                return item;
            });
        });
    } else {
        return false;
    }
};

There are two functions:- One is used for fetching users name and one is used for fetching staffs name. I want both this functions to call on the same input. But the typeahead is getting list of staff members only. Is there any way to get both list populated in the same input.

Upvotes: 0

Views: 61

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Define a new function that does both requests and merges the results.

scope.getAllNames = function(key) {
    var obj = {
        "key": key
    }

    function extract(resp) {
        return resp.data.slice(0)
    }
    if (key.length >= 2) {
        return Promise.all([
          ApiServices.getAllUsers(obj).then(extract), 
          ApiServices.getAllStaffs(obj).then(extract)
        ])
        .then(function(results) {
            return [].concat.apply([], results) 
        });
    } else {
        return false;
    }

}

Upvotes: 1

Related Questions