how to make Generic method for rest call in angularjs - 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'
});

Related

$cancelRequest is not a function

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
});

Get the response using ngResource

I created a factory where I have a method forming the object 'create' and the controller causes through submit REST command. Now I would like a response data because the console I can see that the request was successful. How to do it ? How to get the response? I would add that for me it numeral 32.
app.factory('Claims', ['$resource', function($resource) {
return $resource('/portal/rest/registerClaim', null,
{
'create': { method: 'POST' }
});
}]);
app.controller('ClaimCtrl', ['$scope', 'Claims', function($scope, Claims) {
$scope.registerClaim = function (PIN) {
console.log(PIN);
var obj = {
"t":t,
"a":"t",
"b":"z",
"c":"x",
"d":"q"
};
var a= Claims.create(obj);
console.log(a);
}
}]);
methods of ngResource is asynchronous, so you can get response using $promise
you can read this document about $resource.
https://docs.angularjs.org/api/ngResource/service/$resource
I changed your code in here.
app.factory('Claims', ['$resource', function($resource) {
return $resource('/portal/rest/registerClaim', null,
{
'create': { method: 'POST' }
});
}]);
app.controller('ClaimCtrl', ['$scope', 'Claims', function($scope, Claims) {
$scope.registerClaim = function (PIN) {
console.log(PIN);
var obj = {
"t":t,
"a":"t",
"b":"z",
"c":"x",
"d":"q"
};
Claims.create(obj).$promise.then(function(resp) {
$scope.resp = resp;
});
}
}]);

How can i use Restful in angularjs.I used ngResource but its not working .The js file nt executing if i used ngResource

var app = angular.module('app', ['ngResource']);
app.factory('UserFactory', function ($resource) {
return $resource('/com/vsoft/rest/users', {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
});
app.controller('MyCtrl1', ['$scope', 'UserFactory', function ($scope, UserFactory) {
UserFactory.get({}, function (userFactory) {
$scope.firstname = userFactory.firstName;
$scope.lastname = userFactory.lastName;
});
});
}]);
i added above app in my html.But the app and angular-resource.js but my app.js is not exeuting.
If i removed ngResource module and $resource alert is coming.But if i used ngResource im nt getting alert.
Please help in this.If any one knows any Good Example to use Restful services with angularjs .Please Kindly send Url or code.
Please help me.
i called{{firstname}}
in my html but its not coming .
I use a service for handling RESTful messages
app.service('restService', function ($http, $log) {
'use strict';
var self = this;
var BASE_URL = "base/url/";
//First way how to do it
self.httpGet = function (url) {
$log.info("HTTP Get", url);
return postProcess($http({method: 'GET', url: BASE_URL + url}));
};
//Second way how to do it
self.httpPut = function (url, object) {
$log.info("HTTP Put", url);
return postProcess($http.put(BASE_URL + url, object));
};
self.httpPost = function (url, object) {
$log.info("HTTP Post", url);
return postProcess($http.post(BASE_URL + url, object));
};
self.httpDelete = function (url) {
$log.info("HTTP Delete", url);
return postProcess($http.delete(BASE_URL + url));
};
function postProcess(httpPromise) {
return httpPromise.then(function (response) {
if (response.status === 200) {
return response;
}
//Other than 200 is not ok (this is application specific)
failure(response);
}, function (response) {
failure(response);
});
}
/**
* Promise for failure HTTP codes
* #param response the HTTP response
*/
function failure(response) {
//Error handling
}
});
usable as
restService.httpGet("categories").then(function (response) {
categoryData = angular.fromJson(response.data);
//Broadcast an event to tell that the data is ready to be used
$rootScope.$broadcast("categoriesReady");
});

How to implement passing of variable from one service method to another angular

Hi to all angular guru,
My question is how to pass the return result of one service method to the other methods. Or to make it short I have an authentication method in my service, the return object result for this is a token. The token will be used to be append in my header for the rest of my http request which reside on the same service.
E.g
my Service js
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
})
.then(function(result) {
return result.data.token; //this is now the token
}, function (result) {
console.log(result);
});
}
within the Service js, I have other $http request such as:
getPlayerByEmail: function(email_address) {
return $http({
method : 'GET',
url : api + 'player/' + email_address,
headers : {'X-token': token}
//token here is from the authenticatePlayer method but how to get it??
})
.then(function(result) {
return result.data;
});
}
The two services methods are called in two controllers, my extended question is how to you pass the $scope from one controller to another that even when the page is refreshed the $scope value won't be destroy.
Hope it make sense.
One way to share $scope values between controllers is to create a service and inject it in any controller you want;
An example service,
angular.module('myApp', [])
.service('shareScope', function () {
return {
get: function () {
return value;
},
set: function(data) {
value = data;
}
};
});
In your controller;
function Ctrl($scope, shareScope) {
$scope.prop2 = shareScope.set('data');
$scope.both = shareScope.get();
}
Store it in a variable:
angular.module('foo').factory('someService', function() {
var token;
return {
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
})
.then(function(result) {
token = result.data.token; //this is now the token
}, function (result) {
console.log(result);
});
},
getPlayerByEmail: function(email_address) {
return $http({
method : 'GET',
url : api + 'player/' + email_address,
headers : {'X-token': token}
})
.then(function(result) {
return result.data;
});
}
};
});

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