How to store REST api result in service to avoid requerying - angularjs

service
app.factory('Notes', ['$resource', function($resource) {
return $resource('/notes/:id', {id: '#id'},
{
'query': {method: 'GET', params: { format: 'json'}, isArray: true},
'update': {method:'PUT'},
'save': {method:'POST'},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
},
{ stripTrailingSlashes: false}
);
}]);
Controller:
app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
function($scope, $routeParams, Notes) {
$scope.notes = Notes.query();
Notes.query(
function(data) {
$scope.notes = data;
// success handler
},
function(error) {
alert('error')
// error handler
}
);
}]);
If we are using Notes service in multiple controller it will fetch data again and again.
How to avoid fetching data? I want to fetch data only once and then serve same data to every controller.

Related

Cannot use $http within angular factory (angular 1.x)

I have added $http at the start of the script but for some reason the $http isn't loaded - how do I log $http into the module rather than the controller
var abcdReportServices = angular.module('abcdReportServices', [ ]);
abcdReportServices.factory('uploadFileAjax', ['getPDFsImage', function(getPDFsImage) {
return function(evt, $scope){
$scope.http({
method: "POST",
url: 'someEndpoint/doSomething',
data: $.param({
'name': 'name-of-rpt'
}),
headers: {
"Content-Type" : "application/x-www-form-urlencoded"
}
}).success(
function(data) {
console.log("Saving success", data);
}
);
}
}
}]);
// error in console log
$http is not defined...
You just need to include $http in your factory's dependency injection and then switch your $scope.http to $http.
var abcdReportServices = angular.module('abcdReportServices', [ ]);
abcdReportServices.factory('uploadFileAjax', ['getPDFsImage', '$http', function(getPDFsImage, $http) {
return function(evt){
$http({
method: "POST",
url: 'someEndpoint/doSomething',
data: $.param({
'name': 'name-of-rpt'
}),
headers: {
"Content-Type" : "application/x-www-form-urlencoded"
}
}).success(
function(data) {
console.log("Saving success", data);
}
);
}
}
}]);

Unable to get result of asynchronous call in the controller $scope

I was trying to improve the code in my application by moving the RESTful call in my angularJS to a factory like so:
In app.js
var myApp = angular.module('myApp', ['ngRoute','ngResource']);
In services.js
swof.factory('engineerService', function($resource)
{
var data = $resource('/api/engineers/:empid',{empid: "#empid"},
{
'get':
{ method:'GET'},
'save':
{method:'POST'},
'query':
{method:'GET',
transformResponse: function(data)
{
return angular.fromJson(data);
},
isArray:true},
'remove':
{method:'DELETE'},
'delete':
{method:'DELETE'}
});
return data;
});
In controller.js
engineerService.query().$promise.then(function(data)
{
$scope.engineers = data;
typeof $scope.engineers;
console.log("[in]", $scope.engineers);
$scope.$apply;
});
console.log("[out]", $scope.engineers);
The controller is referenced in the engineer.html page and the idea is that it will display a list of engineers from $scope.engineer.
The output in the Chrome console is as follows:
For some reason I am unable to get the data returned from the REST query to appear outside of the section of the controller with the $promise.
Can someone please help me with this?
Here is the solution. First of all the services part:
swof.factory('engineerService', function($resource)
{
var data = $resource('/api/engineers/:empid',{empid: "#empid"},
{
'get':
{ method:'GET'},
'save':
{method:'POST'},
'query':
{method:'GET',
transformResponse: function(data)
{
return angular.fromJson(data);
},
isArray:true},
'remove':
{method:'DELETE'},
'delete':
{method:'DELETE'}
});
return data;
});
Now for the controller:
swof.controller('engineerController', ['$scope', '$log', '$http', 'engSchedService', 'engineerService', function($scope, $log, $http, engSchedService, engineerService ) {
engineerService.query().$promise.then(function(data)
{
$scope.engineers = data;
});
}]);
The values in $scope.engineers was accessed in html using ngrepeat as follows:
<tbody ng-repeat="engineer in (filtered = (engineers | filter: query | filter: searchKeyword | orderBy: orderByField:reverseSort))">
Big thanks to everyone who contributed to help me with this. G

How to make $resource.post call without sending data

I have done this using $http.post as below:
$http({
method: 'POST',
url: 'www.someurl'+myid
}).then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response)
});
Requirement is to make the same post call using $resource. I tried as below:
filter:
saffModuleServices.factory('Projects', ['$http', '$resource', '$appConstants',
function ($http, $resource, $appConstants) {
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
var createDraftEndPoint=www.someurl/:id;
var saveEmailDraftEndPoint=www.someurl.com
return {
saveEmailDraft: function(){
return $resource(saveEmailDraftEndPoint, {}, {
update: {method: 'PUT', params: {},headers: {'Content-Type':'application/json'}}
});
},
createDraft: function(){
return $resource(createDraftEndPoint, {}, {
post: {method: 'POST',param{id:''}}
});
},
}
}]);
controller:
saffModuleControllers.controller('ctrl', ['$scope', 'SaffNotification','Projects','$filter',
function ($scope, Notification,Projects,$filter) {
Projects.createDraft().post({id:myid}, function(response){
Notification.success({message: $filter('translate')('administration_item_save_notification'), templateUrl: 'common/templates/toastr_success_template.html'});
}, function(response){
Notification.error({message: response.data.errorMessage, templateUrl: 'common/templates/toastr_error_template.html'});
});
}]);
error:
myId is going as data for this request, but I want to send that as param and no data should be sent. I could do that using $http.post
Can anyone suggest me how to make this request in $resource.post without editing $httpProvider in config, because I dont want to make 'data' parameter nil for other POST request.

I don't know how to use this angularjs options

I update the question now .
Mi view HTML
<a class="btn btn-success" ng-click="eliminartodo()">Eliminar todos</a>
Now I send my Controller Angular
.controller('ListCtrl', function($scope,$routeParams,Node,User) {
$scope.nodes = Node.query();
/**DeleteAll**/
$scope.eliminartodo = function () {
$scope.nodes = [];
};
})
And my Factory
nodeServices.factory('Node', ['$resource',
function($resource){
return $resource('api/nodes/:nodeId', {}, {
'get': {method:'GET', params:{nodeId:'#nodeId'}, isArray:false},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'update': {method:'PUT'},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
});
}]);
In another code I use this and working properly
Node.remove({nodeId: nodeId}, $scope.node, function() {
$timeout(function() {
$location.path('/');
});
});

angularjs factory with $resource doesn't work

This is my angularjs factory :
app.factory('lordREST', ['$resource', function($resource){
return {
myPost: function(dataSearch, dataParam) {
$resource(
urlLordRest,
{search: dataSearch, param: dataParam},
{'query': {method: 'GET', isArray: true, cache: false, headers: {'Accept': 'application/json'}}}
);
}
}
}]);
and in my controller i use it like that :
lordREST.myPost({dataSearch: dataSearch, dataParam: dataParam}, function(responce) {
$scope.posts = responce;
// CONSOLE LOG CONTROL
// console.log(defineCLC + "data changed");
console.log($scope.posts);
});
But this action return nothing, what's wrong ?

Resources