Circular dependency angularjs - angularjs

can anyone tell me where is the circular dependency in the following code?
var homeApp = angular.module("homeApp",['ngAnimate', 'ui.bootstrap']);
'use strict';
homeApp.factory('AdminDashboardService', ['$http', '$q', function($http, $q){
return {
'response': function(response) {
// do something on success
console.log("Yes Command comes here");
return response;
},
getAllHolidays: function(monthYearArrayForHolidayList) {
console.log("For full list of holidays list length: "+monthYearArrayForHolidayList.length);
var isMonthly="no";
return $http.get('/tasktrac/holiday/getHoliday/isMonthly/'+isMonthly+'/'+monthYearArrayForHolidayList)
.then(
function(response){
return response.data;
},
function(errResponse){
//console.error('Error while fetching holiday');
return $q.reject(errResponse);
}
);
},
}]);
homeApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('AdminDashboardService');
}]);
I am stuck at this point please do me a favour in resolving this issue.
This is the Error I got on the browser
Please click here to see error
Thank you..!!

A $http interceptor could not declare $http as a dependency!
Inject $injector:
homeApp.factory('AdminDashboardService', ['$injector', '$q', function($injector, $q){
return {
'response': function(response) {
// do something on success
console.log("Yes Command comes here");
return response;
},
getAllHolidays: function(monthYearArrayForHolidayList) {
console.log("For full list of holidays list length: "+monthYearArrayForHolidayList.length);
var isMonthly="no";
return $injector.get("$http").get('/tasktrac/holiday/getHoliday/isMonthly/'+isMonthly+'/'+monthYearArrayForHolidayList)
.then(
function(response){
return response.data;
},
function(errResponse){
//console.error('Error while fetching holiday');
return $q.reject(errResponse);
}
);
},
}]);

Related

How to propagate error in httpProvider responseError interceptor

We have the following code in place for form validation:
$scope.masterModel.$save().then(function (data) {
$scope.masters.data.push(data);
$location.path('/master/edit/' + data.id);
}).error(function (data) {
$scope.errors = data.data;
});
Now we added code to generally catch code 500 server errors on a global level to the app.js
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(function ($injector) {
return {
'responseError': function (rejection) {
// do something on error
if (rejection.status === 500) {
var angularModalService= $injector.get("ModalService");
angularModalService.showModal({
templateUrl: "templates/common/session.html",
controller: "ModalController"
}).then(function (modal) {
modal.element.modal();
modal.close.then(function (result) {
if (result) {
}
});
});
}
}
};
});
}]);
As soon as we add this code, the error callback in the first code does not work anymore.
I think we have to somehow propagate the error in the responseError callback, but how does that work?
AngularJS Version is 1.5.11
You need to "reject the rejection" in the interceptor and return it in order for the error to be propagated:P
var app= angular.module('MyApp', []);
app.controller('Controller', function($scope, $http, $q) {
$http.get("http://www.example.invalid/fake.json")
.then(function(response) {
console.log("success");
}, function(error) {
console.log("controller error handler");
});
});
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(function ($injector, $q) {
return {
'responseError': function (rejection) {
console.log("interceptor error handler");
// do something on error
if (rejection.status === 500) {
// do something...
}
return $q.reject(rejection);
}
};
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="Controller">
</div>
</div>
As you can see, I added the line
return $q.reject(rejection);
at the end of your interceptor. You can check the console and see that now both messages are logged.

Need to call AngularJS function on every ajax request

I need to call one of my AngularJS function on every Ajax request that my application makes and I want to do it AngularJS Way (not a classic JS/JQuery Way)
Here is my code :
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$location', '$q', function($location, $q) {
return {
'request': function(request) {
// My angularJS Function goes here.
return request;
},
'responseError': function(response) {
return $q.reject(response);
}
};
}]);
}])
but it's not working some how.
No Error - No output on console. Help is highly appreciated.
Found duplicate $httpProvider.interceptors causing this issue. Fixed, now it's working fine.
Try this one
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$location', '$q', function($location, $q) {
var requestPromise = {
request: function(request) {
// My angularJS Function goes here.
return request;
},
responseError: function(response) {
return $q.reject(response);
}
};
return requestPromise;
}]);
}])

Update data from a factory in another factory

I have two factories in my angular app.
app.factory('FavoritesArtists',['$http', '$q', 'UserService', function($http, $q, UserService){
var deferred = $q.defer();
var userId = UserService.getUser().userID;
$http.get('http://myurl.com/something/'+userId)
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}]);
And I have a value I get from another factory :
var userId = UserService.getUser().userID;
But I doesn't update when the UserService.getUser() is changed, the view changes with $watch, but I don't know how it work inside a factory.
Any help is welcome, thanks guys !
Anyone ?
app.factory('FavoritesArtists',['$http', '$q', 'UserService', function($http, $q, UserService){
var deferred = $q.defer();
$http.get('https://homechefhome.fr/rise/favorites-artists.php?user_id='+userId)
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}]);
I simply need to make userId variable dynamic..
A better design pattern will be this
app.factory('UserService',
['$http', function($http) {
var getUser = function() {
return http.get("url_to_get_user");
};
return {
getUser: getUser
};
}]);
app.factory('ArtistService',
['$http', '$q', 'UserService', function($http, $q, UserService) {
var getFavoriteArtists = function() {
UserService.getUser().then(function(response) {
var userId = response.data.userID;
return $http.get('http://myurl.com/something/' + userId);
}, function() {
//passing a promise for error too
return $q.reject("Error fetching user");
});
};
return {
getFavoriteArtists: getFavoriteArtists
};
}]);
Now call it in controller like,
ArtistService.getFavoriteArtists().then(function(response) {
//do something with response.data
}, function(response) {
//log error and alert the end user
});

How to display error on the page after service return an error to the controller in angular js?

Now I have tried to display the response which is returned from the service to the controller..When I am trying to display the error its not working.The below is the code which i have tried
var app=angular.module('httpExample',[]);
app.controller("FetchController",["$scope","clickevent",function($scope,clickevent){
clickevent.fetch().then(function(response){
$scope.req=response;
console.log(angular.toJson(response));
}).error(function(error){
console.log(error);
});
}]);
app.service("clickevent",['$http',function($http){
var clickevent={
fetch:function(){
var prom=$http({method:"GET",url:"http://www.w3schools.com/angular/customers.php"}).
success(function(response){
return response;
}).
error(function(err){
return err;
});
return prom;
}
};
return clickevent;
}]);
Promises don't have an error() function. They have a catch() function. success() and error() are specific to promises returned by $http, and those deprecated functions don't allow chaining like then() and catch() allow.
Here's how your code should look like:
var app = angular.module('httpExample',[]);
app.controller("FetchController",["$scope", "clickevent", function($scope, clickevent){
clickevent.fetch().then(function(data) {
$scope.req = data;
console.log(angular.toJson(data));
}).catch(function(error) {
console.log(error);
});
}]);
app.service("clickevent",['$http', '$q', function($http, $q){
var clickevent = {
fetch: function() {
var prom = $http({method:"GET",url:"http://www.w3schools.com/angular/customers.php"}).
then(function(response) {
return response.data;
}).
catch(function(response) {
return $q.reject(response.data);
});
return prom;
}
};
return clickevent;
}]);

Is there a way I can return a promise from a $resource without needing to use $q?

I have coded the following service:
angular.module('App')
.factory('TestService', ['$http', '$q', '$resource', function (
$http, $q, $resource) {
var TestResource = $resource('/api/Tests', {}, {
saveData: { method: 'PUT' },
deleteData: { method: "DELETE", params: { TestId: 0 } }
});
var factory = {
query: function (selectedSubject) {
var deferred = $q.defer();
TestResource.query({ subjectId: selectedSubject },
function (resp) {
deferred.resolve(resp);
}
);
return deferred.promise;
//return Test.query({ subjectId: selectedSubject });
}
}
return factory;
}]);
In my controller I am calling it this way:
TestService.query($scope.selectedSubject)
.then(function (result) {
$scope.gridData = result;
}, function (result) {
alert("Error: No data returned");
});
Is there a way that I could cut out a few lines of code by not having $q in my service. Is there a way that I could return a promise from the $resource? I have tried the commented out code but that gives me an error saying there is no ".then" method.
$resource can't return a promise in the current stable version of Angular (1.0.8), but it looks like it'll come in version 1.2. It was added in v1.1.3 (v 1.1 is the unstable branch):
$resource: expose promise based api via $then and $resolved (dba6bc73)

Resources