$cancelRequest is not a function - angularjs

I'm using angularjs 1.5.8.
I get this error when I'm trying to cancel an http request with angular :
$cancelRequest is not a function
My code :
app.factory('User', function($resource) {
var getUsersResource = $resource(
'/users',
null,
{get : {method: 'GET', isArray: true, cancellable: true}}
);
return {
getUsers : function() {
return getUsersResource.get({},
function(data) {
...
}, function(error) {
...
}
);
}
};
});
app.controller('InitController', function($rootScope, User, ...) {
...
User.getUsers();
...
}
app.factory('AuthInterceptor', function($q, $location, $injector) {
return {
responseError: function(response) {
if (response.status === 401) {
$injector.get('$http').pendingRequests.forEach(
function (pendingReq) {
pendingReq.$cancelRequest();
}
);
$location.path('login');
}
return $q.reject(response);
}
};
});
Do you know how I can solve this error ?
Thanks

The documentation suggests that $cancelRequest should be used with the resource object. From my initial review, it appears that you're correctly using $resource within the User factory. But, I'm not sure about how you're implementing this within the AuthInterceptor factory. It doesn't look like you're using User.getUsersSources() at all. Therefore, I believe the reason that you're getting that error is because you're not using $cancelRequestion correctly. That being said, you might have forgotten to include other parts of the code.
Ideally, the resolved $resource object from User.getUserResources() should be passed into AuthInteceptor.

I think that you should declare your service like that:
.factory('categoryService', ['$resource', function($resource) {
return $resource('/', {},
{
'get': {
'method': 'GET',
'cancellable': true,
'url': '/service/categories/get_by_store.json',
},
});
}])
And when you use this service, it should be called so:
if ( $scope.requestCategories ) {
$scope.requestCategories.$cancelRequest();
}
$scope.requestCategories = categoryService['get']({
}, function(res){
//some here
}, function(err){
//some here
});

Related

Angularjs-$ngSource-DELETE: How to get response data which the server side returns?

Why the console.log(response) didn't inculde the response from server. How can I get the "1" or "0" which the SpringMVC return?
var app = angular.module('MyApp', ['ngResource']);
app.factory('baseRequest', ["$resource", function ($resource) {
return $resource("/apis/:id/:method/", {method: '#method', id: '#id'}, {
query: {method: 'get', isArray: false}
});
}]);
app.controller("MyCtrl", ["$scope", "baseRequest", function ($scope, baseRequest) {
$scope.deleteUser = function (id) {
baseRequest.delete({method: "deleteUser.req", id: id}, function (response) {
//I can't get the response data from server side here.
console.log(response);
}, function (error) {
console.log(error);
});
};
}]);
Here is my SpringMVC file, it retruns the information "1" or "0"
,but I don't how to get it?
#ResponseBody
#RequestMapping(value = "/{id}/deleteUser", method = RequestMethod.DELETE)
public String deleteUser(#PathVariable("id") Integer id) {
System.out.println(id);
if (userDao.deleteUser(id)) {
return "1";
} else {
return "0";
}
}
the whole code seems wrong to me. Actually you factory should look like this:
app.factory('baseRequest', ["$resource", function ($resource) {
return $resource("/apis/:id", { id: '#id'}, {
query: {method: 'get', isArray: false}
});
}]);
and you controller should look like this:
app.controller("MyCtrl", ["$scope", "baseRequest", function ($scope, baseRequest) {
$scope.deleteUser = function (id) {
baseRequest.delete({id: id}, function (response) {
//I can't get the response data from server side here.
console.log(response);
}, function (error) {
console.log(error);
});
};
}]);
When you define a resource to an endpoint, angularjs automatically create the four methods(Verbs) (get, delete, put, post) for you. so you don't need to pass the method name to the web api.

$resource not resolving in test

I'm trying to use apiSearch.get().then(func(){...}) I have it working in my tests, but I can't get the data when I use that same method in my controller. Is it even possible to use .then() with a returned resource? If not, is there another solution I can use in my in place of my controller or test code?
service.js
angular.module('app').factory('apiSearch', ['$resource', '$log',
function ($resource, $log) {
return $resource('api/search/:value', {}, {
get: {
method: 'GET',
isArray: false,
cache: true
}
});
}
])
pageService.js
/*** this works when I test it in the browser but makes my test fail ***/
apiSearch.get({value: 'thisvalue'}, function (res) {
$state.go('storefront.home');
}, function (err) {
$state.go('not-found');
})
/*** this works for my test but fails in the browser ***/
apiSearch.get({value: 'thisvalue'}).then(function (res) {
$state.go('storefront.home');
}, function (err) {
$state.go('not-found');
})
test.js
it("Should ", function(){
resolveData = 'itemName'
deferred.resolve(resolveData);
spyOn(apiSearch, "get").and.returnValue(deferred.promise)
$scope.$digest();
expect($state.current.name).toEqual('storefront.home');
});

Angular resource middleware to catch response

I have an angular service that looks like:
service('PortfolioService', ['$resource', function($resource) {
return $resource('/api/', {}, {
stock_positions: {
method: 'GET',
url: '/api/stock_positions',
isArray: false
}
});
}]).
And in a controller:
PortfolioService.stock_positions(function someCB(result){
//do something with the result
});
If you aren't logged in the api returns an object that looks like:
{
error: "Login required",
redirect: "/login"
}
I would like to have something that would catch this in the resource, handle it (redirecting to /login), and not pass on to someCB in the controller.
Is there a way to do this with $resource?
I think this can be achieved by angular interceptor.
https://docs.angularjs.org/api/ng/service/$http
$httpProvider.interceptors.push(['$location', function($location) {
return {
'response': function(response) {
if(response.redirect.indexOf('/login'){
// redirect to login
}
return response;
}
};
}]);
It looks like I just needed to do the following:
service('PortfolioService', ['$resource', function($resource) {
return $resource('/api/', {}, {
stock_positions: {
method: 'GET',
url: '/api/stock_positions',
isArray: false,
interceptor:{
response:function(response){
//do stuff here to catch the response before passing it on.
return response;
},
responseError: function(rejection){
console.log(rejection);
}
}
}
});
}]).

Angular $resource - attach a generic .finally function to a method

I have a generic restful resource with angular's $resource. On any save method, I also want to set a message and boolean on whatever scope I'm in, and set a timeout for that message. So anywhere in my code where I call .save/.$save, I then attach a .finally onto it (below).
Rather than putting the same .finally onto every save I call, I'm wondering if I can just write a finally onto the actual resource itself, and have this be a generic finally for my save function.
var resource = $resource(
pageListPath,
{},
{
query: {method:'GET', isArray:true},
get: {method:'GET', url: pageDetailPath, params:{id:'#id'}, cache:true},
save: {method:'PUT', url: pageSavePath, params:{id:'#id'}},
delete: {method:'DELETE', url: pageDetailPath, params:{id:'#id'}}
}
);
return resource;
.finally(function() {
$scope.loading = false;
$timeout(function() {
$scope.message = false;
}, 2500);
});
Ideally something like
save: {
method:'PUT',
url:pageSavePath,
params:{id:'#id'},
finally:function() { doStuff() }}
is what I'm looking for. Is this possible?
I ended up writing another service to encapsulate this one, providing generic functionality for certain responses.
The API service:
pageServices.factory('PageAPI',
['$resource',
function($resource,
var resource = $resource(
pageListPath,
{},
{
query: {
method:'GET',
isArray:true
},
get: {
method:'GET',
url: pageDetailPath,
params:{ id:'#id' }
},
...,
...,
}
);
return resource;
}]
);
pageServices.factory('Page', ['PageAPI',
function(PageAPI) {
var service = {
'getPages': function() {
return PageAPI.query(function(response) {
// Do stuff with success
}, function(err) {
// Handle error
}).$promise.finally(function() {
// Generic finally handler
}
},
...,
...,
}
return service
}
])

how to make Generic method for rest call in angularjs

how to make Generic method for rest call in angularjs ?
i have tried for single request, it's working fine
UIAppRoute.controller('test', ['$scope', 'checkStatus', function($scope, checkStatus) {
$scope.data = {};
checkStatus.query(function(response) {
$scope.data.resp = response;
});
}])
UIAppResource.factory('checkStatus', function($resource){
return $resource(baseURL + 'status', {}, {'query': {method: 'GET', isArray: false}})
})
I want to make this as generic for all the request
Please share any sample,.. thanks in advance
I'm using something like this :
.factory('factoryResource', ['$resource', 'CONF',
function($resource, CONF) {
return {
get: function(endPoint, method) {
var resource = $resource(CONF.baseUrl + endPoint, {}, {
get: {
method: method || 'GET'
}
});
return resource.get().$promise;
}
};
}
])
called by :
factoryResource.get(CONF.testEndPoint, "POST"); // make a POST and return a promise and a data object
factoryResource.get(CONF.testEndPoint, "GET"); // make a GETand return a promise and a data object
factoryResource.get(CONF.testEndPoint); // make a GETand return a promise and a data object
with a config file having :
angular.module('app.constant', [])
.constant('CONF', {
baseUrl: 'http://localhost:8787',
testEndPoint: '/api/test'
});

Resources