How to write on right way factorys AngularJS - javascript

I found this styleguide for angularjs:
https://github.com/johnpapa/angular-styleguide#factories
I wana now to write my code on that way:
Here is my working factory:
.factory('Noty',function($http){
return{
update:function(NotificationData){
return $http ({
method: "PUT",
url : "/api/notification/" + NotificationData.task,
data : NotificationData
});
}
};
});
How can I rewrite it to look like in document above?
/* recommended */
function dataService() {
var someValue = '';
var service = {
save: save,
someValue: someValue,
validate: validate
};
return service;
////////////
function save() {
/* */
};
function validate() {
/* */
};
}

You'd write it like this:
(function () {
'use strict';
var factoryNotyModule = angular.module('yourApp.factory.Noty', []);
factoryNotyModule.factory('Noty', Noty);
Noty.$inject = ['$http'];
function Noty($http) {
function updateData (NotificationData) {
return $http({
method: 'PUT',
url: '/api/notification/' + NotificationData.task,
data: NotificationData
});
}
return {
updateData: updateData
};
}
})();
So that you can use it after you inject it somewhere:
Noty.updateData(data);

This is pretty simple, as you are already using a factory with the revealing module pattern:
.factory('Noty', function ($http) {
var service = {
update : update
};
return service;
function update(NotificationData) {
return $http({
method : "PUT",
url : "/api/notification/" + NotificationData.task,
data : NotificationData
});
}
});

Related

Why I am getting not a function error in angularjs?

I am following this tutorial I've found at Stormpath.
I am trying to understand how AngularJS works, but I am failing to get the edit function (controller) running. I am always getting the type error:
TypeError: SearchService.fetch is not a function
Within its callstack it references EditController pointing at this line of code:
SearchService.fetch($stateParams.id, function (response) {
Here is the whole code of EditController:
(function () {
'use strict';
angular
.module('myApp')
.controller('EditController', EditController);
EditController.$inject = ['SearchService', '$stateParams'];
function EditController(SearchService, $stateParams) {
var vm = this;
SearchService.fetch($stateParams.id, function (response) {
vm.person = response;
});
}
})();
However I have no clue what's wrong here. I am trying to compare this code with the code for SearchController - please see below,
(function () {
'use strict';
angular
.module('myApp')
.controller('SearchController', SearchController);
SearchController.$inject = ['SearchService'];
function SearchController(SearchService) {
var vm = this;
vm.search = function(){
SearchService.query(vm.term, function (response) {
var results = response.filter(function (item) {
return JSON.stringify(item).toLowerCase().includes(vm.term.toLowerCase());
});
vm.searchResults = results;
});
}
}
})();
Here is the code for SearchService:
(function () {
'use strict';
angular
.module('myApp')
.factory('SearchService', SearchService);
SearchService.$inject = ['$resource'];
function SearchService($resource) {
return $resource('/api/search/people.json');
}
SearchService.fetch = function (id, callback) {
Search.query(function (response) {
var results = response.filter(function (item) {
return item.id === parseInt(id);
});
return callback(results[0]);
});
};
})();
Any piece of advice is appreciated, I've spent already couple of days trying out various things.
Make your search service like this..
The service factory function generates the single object or function that represents the service to the rest of the application. The object or function returned by the service is injected into any component (controller, service, filter or directive) that specifies a dependency on the service
https://docs.angularjs.org/guide/services
(function () {
'use strict';
angular.module('myApp')
.factory('SearchService', SearchService);
SearchService.$inject = ['$resource'];
function SearchService($resource, $http) {
var service = {};
service.url = $resource('/api/search/people.json');
var req = {
method: 'GET',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
service.fetch = function (id, callback) {
// $http.get('yourapi.json').then() you can try like this also
return $http(req).then(function (response) {
var results = response.filter(function (item) {
return item.id === parseInt(id);
});
return callback(results[0]);
});
};
return service;
}
})();

Angular can't retrive simple Integer as a backend reposne

From the backend I'm getting simple integer:
#PreAuthorize("hasAnyAuthority('WORKER')")
#RequestMapping(value = "/countFiles", method = RequestMethod.GET)
public ResponseEntity<Integer> countFiles(HttpServletRequest request){
return fileService.countFiles(request);
}
UPDATE - Service site:
public ResponseEntity<Integer> countFiles(HttpServletRequest request) {
Principal name = request.getUserPrincipal();
if (name.getName() == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
User userByLogin = userRepository.findUserByLogin(name.getName());
fileDao.countByUser(userByLogin);
return new ResponseEntity<Integer>(fileDao.countByUser(userByLogin), HttpStatus.OK);
}
At frontend site created simple method:
angular.module('sbAdminApp').factory('FileService', function ($resource) {
var service = $resource('api/file', {
id: '#id'
}, {
saveFile: {
method: 'POST',
url: 'api/file',
headers: {'content-Type': undefined}
},
countFiles: {
method: 'GET',
url: 'api/file/countFiles',
responseType: 'text'
}
});
return service;
});
Angular controller:
var app = angular.module('sbAdminApp');
app.controller('GoogleMapCtrl', function ($scope, $log, uiUploader, FileService, $http) {
$scope.name = "Hello";
console.log('count', FileService.countFiles());
});
But the output looks like:
So there is no my clount at all..It should be 27.
================UPDATE=====================
var val;
FileService.countFiles().$promise.then(function(response) {
console.log('respone', response.data);
val = response.value();
});
console.log('val', val)
Abouve code return both for var and when I print undefinded
Your Service/Factory method 'countFiles' returns a promise. So you have to "wait" for the promise to be resolved.
FileService.countFiles().$promise.then(function(response) {
$scope.val = response.value();
}
The console.log('val', val) would get executed first if written outside since we wait for the promise to get resolved. So, it should be,
var val;
FileService.countFiles().$promise.then(function(response) {
console.log('respone', response.data);
//val = response.value;
//console.log('val', val);
});

How to refresh the ui-grid while leaving rendered filters intact?

I need to refresh the ui grid and leave the site and the filters intact. How can I do that?
Right now I'm using this inside a controller:
$scope.refresh = function () {
$state.reload();
};
so my teammates were able to find an answer - all you have to do is reset the data source (reset the source to gridOptions.data):
$scope.refresh = function () {
$scope.refreshGridData();
};
$scope.refreshGridData = function () {
files.getfiles().success(handleSuccess).error(handleError);
}
and
angular.module('name.service', [
])
.factory('files', ['$http', function ($http) {
return {
getfiles: function () {
var params = {
...
};
return $http({
method: 'POST',
url: '/url/to/api/function',
data: JSON.stringify(params)
});
}
}
}]);
Thanks for the help! :)

change variable in angularjs factory using $resource

In my AngularJS app I want a factory with a method to change a variable in the factory itself by using $resource. The code I have written so far is the following:
factories.factory('FooFactory', function ($resource) {
var foo = null;
return {
query: function () {
foo = $resource(baseUrl + '/someUrl/:query', {}, {
query: { method: 'GET', isArray: true }
});
},
getFoo: function () {
return foo;
}
}
});
So when calling FooFactory.query({query: "someString"}); I want the factory to change the value of foo to the value received from the resource.
I need this behaviour because the value of foo is changed by a directive and I need to bind its value to a value in the scope of a controller.
However, the code above doesn't seem to work. What am I doing wrong?
You do not call any method of resource you only initialize it. Try this:
factories.factory('FooFactory', function ($resource) {
var foo = null;
return {
query: function () {
foo = $resource(baseUrl + '/someUrl/:query', {}, {
query: { method: 'GET', isArray: true }
}).query();
},
getFoo: function () {
return foo;
}
}
});

How to write a multiple Aync Function within a Service in AngularJS

Im just starting on AngularJS. I'm not sure how to churn this out. I'm trying to include multiple functions within one service. (I hope this is not against bad practice.)
The following is my working code:
myDataService.async().then(function (d) {
$scope.dbCalls = d.d;
});
My Service:
app.factory('myDataService', function ($http) {
// How do you get this bottom line to work?
// this.getAllCalls = function () {
var myService = {
async: function () {
var promise = $http.post('AngularTest.aspx/FetchCalls', { data: {} }).then(function (response) {
console.log(response);
return response.data;
});
return promise;
}
};
return myService;
//}; <--Commented out for clarity
});
Thanks!
you just return an object with properties from the service, then you are able to call those properties as different service methods
like so:
.service('myService', function() {
return {
firstMethod: function() { ... },
secondMethod: function() { ... },
thirdMethod: function() { ... }
}
})
and in the controller/directive
.controller('myCtrl', function(myService) {
myService.firstMethod();
myService.secondMethod();
myService.thirdMethod();
})

Categories