I am trying to search form that will invoke and return ajax call only if the parameter contains 6 or more characters.
In my controller, I have a simple function.
function getByParam(param) {
if (param.length >= 6) {
return $http.get('https://example.com/endpoint/' + param);
} else {
return noItems();
}
}
The trouble is with returning a promise with an empty response set. Whatever I seem to try results in an error.
myController.getByParam(param).success is not a function
Currently I have this as the noItems() function.
function noItems() {
var promise = Promise(function(resolve, reject) {
if (true) {
resolve();
} else {
reject();
}
}).then(function(){
var emptyResponse = {success:true, response:{records:[]}}
return emptyResponse
});
return promise
}
I have seen answers involving $httpBackend but this seems like overkill. I have also seen suggestions using $timeout but again, I'm missing something to get it to work.
spyOn('$http, 'get')? $httpBackend is not overkill but the recommended way of HTTP mocking in Angular.noItemsuses native Promise (is processed asynchronously), while $http uses $q promise (is processed synchronously and depends on digest cycle). And mocking $http request withPromisewon't make it processed in the same way. Please, elaborate on the choice of promise implementation.