Feeling a bit unsure about my approach...
I'm diving into my first AngularJS app and trying to grasp the architecture.
So, I've built a service called isAjax
, utilizing the $http
module to handle API calls for me.
I'm capturing the success and error responses in this service.
Here's the code - not entirely sure if the syntax is correct, but it seems to be working...
appServices.factory('isAjax', ['$http', '$q', function ($http, $q) {
var apiController = function (url) {
if (url.indexOf('?') > -1){
return url.substring(url, url.indexOf('?'));
} else {
return url;
}
}
var doHttp = function (url, method) {
var deferred = $q.defer();
$http({
method: method,
url: url
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data, status) {
switch (status) {
case 404:
bootbox.alert('api call to ' + apiController(url) + ' failed<br />URL does not exist');
break;
case 401:
// Here - I would like to somehow call a directive? which would open a bootstrap modal and load a view into it.
break;
default:
console.log(arguments);
bootbox.alert('ajax error');
}
console.log(status);
console.log('http errored')
});
return deferred.promise;
};
return {
getData: function (url, method) {
return doHttp(url, method);
}
}
}]);
To use this service, I just need to inject isAjax
and then call:
var dataPromise = isAjax.getData('api/globaljson', 'get');
Now, when I encounter a status code 401
, I want to trigger something - possibly a directive - that will display a view in a modal.
This is where I'm hitting a roadblock... If I create a directive, how can I communicate with it from the service?
I could potentially create another service to handle it, but I know that manipulating the DOM shouldn't be done in a service.
Any guidance would be greatly appreciated.
Thanks!