Custom method in an Angular service using $resource in Jhipster - angularjs

I don't understand the syntax to write a custom method in an Angular Service using $resource in Jhipster. After a lot of research, I am doubtful whether it's even possible.
Here is the code for Angular Service.
(function() {
'use strict';
angular
.module('tealboxApp')
.factory('Task', Task);
Task.$inject = ['$resource', 'DateUtils'];
function Task ($resource, DateUtils) {
var resourceUrl = 'api/tasks/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.assignedDateTime = DateUtils.convertDateTimeFromServer(data.assignedDateTime);
data.startDateTime = DateUtils.convertDateTimeFromServer(data.startDateTime);
data.endDateTime = DateUtils.convertDateTimeFromServer(data.endDateTime);
data.startDate = DateUtils.convertLocalDateFromServer(data.startDate);
data.endDate = DateUtils.convertLocalDateFromServer(data.endDate);
}
return data;
}
},
'update': {
method: 'PUT',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.startDate = DateUtils.convertLocalDateToServer(copy.startDate);
copy.endDate = DateUtils.convertLocalDateToServer(copy.endDate);
return angular.toJson(copy);
}
},
'save': {
method: 'POST',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.startDate = DateUtils.convertLocalDateToServer(copy.startDate);
copy.endDate = DateUtils.convertLocalDateToServer(copy.endDate);
return angular.toJson(copy);
}
}
});
}
})();
I want to add a custom method like...
'getTasksWithXYZ': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.assignedDateTime = DateUtils.convertDateTimeFromServer(data.assignedDateTime);
data.startDateTime = DateUtils.convertDateTimeFromServer(data.startDateTime);
data.endDateTime = DateUtils.convertDateTimeFromServer(data.endDateTime);
data.startDate = DateUtils.convertLocalDateFromServer(data.startDate);
data.endDate = DateUtils.convertLocalDateFromServer(data.endDate);
}
return data;
}
}
I am not sure how to pass a parameter to this get method or even how to call this method in the controller. How does one do this?

In your service add params
return $resource(resourceUrl, {}, {
'getTasksWithXYZ': {
method: 'GET',
params:{id:'#id'},
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.assignedDateTime = DateUtils.convertDateTimeFromServer(data.assignedDateTime);
data.startDateTime = DateUtils.convertDateTimeFromServer(data.startDateTime);
data.endDateTime = DateUtils.convertDateTimeFromServer(data.endDateTime);
data.startDate = DateUtils.convertLocalDateFromServer(data.startDate);
data.endDate = DateUtils.convertLocalDateFromServer(data.endDate);
}
return data;
}
}
})
In your controller Task.getTasksWithXYZ(id)

Related

GET call to REST API returns null

I am trying to make a GET call to test a REST API but it keeps returning null, is there anything I am doing wrong:
Making the call in controller.js
function ConsumerSearchCtrl($scope, BusinessCategoryService) {
console.log(BusinessCategoryService);
}
127.0.0.1:8000/api/category/ works perfectly fine
Code in services.js for API
/**
*
*/
function BusinessCategoryService(WenzeyAPI, $q) {
var scope = this;
scope.categories = categories;
function categories() {
var q = $q.defer();
WenzeyAPI.get('http://127.0.0.1:8000/api/category/').then(function success (res) {
q.resolve(res.data);
}, function failure (err) {
q.reject(err);
})
return q.promise;
}
}
/**
*
*/
function WenzeyAPI() {
var scope = this,
ip = "http://127.0.0.1:8000";
scope.get = get;
scope.post = post;
function get(url, data) {
data = data || {};
var req = {
method: 'GET',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
function post(url, data) {
data = data || {};
var req = {
method: 'POST',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
}
Removing WenzeyAPI and using $http resolved it.
function BusinessCategoryService($http) {
this.getAllData = function () {
return $http({
method: 'GET',
url: 'http://127.0.0.1:8000/api/category/',
});
}
}

Common transformResponse in factory $resource

We are using a factory to interact with a series of custom APIs around common entities. However, part of what I need to do is evaluate the custom responses sent back in the headers and it seems like they way to do this is to use transformResponse. What I have seems to be working, but I'm literally repeating the same thing over and over in each definition. I tried creating a function to make it reusable, but the reference seems to fail. What am I doing wrong?
(function()
{
'use strict';
angular.module('aumBills', ['ngResource'])
.factory('Bills', ['$resource',
function($resource)
{
return $resource(
'/ua_aumcore/bills/api/v1/bills/:billableEventI',
{
billableEventI:'#billableEventI'
},
{
getList:
{
method: 'GET',
isArray: false,
transformResponse: function(data, header, status, config, statusText)
{
var response = {};
if (isJson(data))
{
data = angular.fromJson(data);
response.data = data;
}
response.status = status;
response.config = config;
response.statusText = statusText;
return response;
},
url: '/ua_aumcore/bills/api/v1/bills/query/'
},
getParties:
{
method: 'GET',
isArray: false,
transformResponse: function(data, header, status, config, statusText)
{
var response = {};
if (isJson(data))
{
data = angular.fromJson(data);
response.data = data;
}
response.status = status;
response.config = config;
response.statusText = statusText;
return response;
},
url: '/ua_aumcore/bills/api/v1/customer/billParties/?partySites=:partySiteIDs',
params: {partySiteIDs: '#partySiteIDs'}
}
//plus about 12 more after this
});
}]);
function isJson(str)
{
try
{
JSON.parse(str);
}
catch (e)
{
return false;
}
return true;
}
})();
The code that broke looked identical to above, only I put:
transformResponse: transResp(data, header, status, config, statusText),
in each definition, and then this is the function that follows immediately after isJSON:
function transResp(data, header, status, config, statusText)
{
var response = {};
if (isJson(data))
{
data = angular.fromJson(data);
response.data = data;
}
response.status = status;
response.config = config;
response.statusText = statusText;
return response;
}
It looks like defining the transformResponse function I want to use as a variable, and plugging the variable into the definition works:
(function()
{
'use strict';
angular.module('aumBills', ['ngResource'])
.factory('Bills', ['$resource',
function($resource)
{
var transResp = function(data, header, status, config, statusText)
{
var response = {};
if (isJson(data))
{
data = angular.fromJson(data);
response.data = data;
}
response.status = status;
response.config = config;
response.statusText = statusText;
return response;
};
return $resource(
'/ua_aumcore/bills/api/v1/bills/:billableEventI',
{
billableEventI:'#billableEventI'
},
{
get:
{
method: 'GET',
isArray: false,
transformResponse: transResp,
url: '/ua_aumcore/bills/api/v1/bills/:billableEventI'
},
getList:
{
method: 'GET',
isArray: false,
transformResponse: transResp,
url: '/ua_aumcore/bills/api/v1/bills/query/'
}
//and so on and so forth
});
}]);
function isJson(str)
{
try
{
JSON.parse(str);
}
catch (e)
{
return false;
}
return true;
}
})();

Angularjs - $resource as a service, issue with multiple urls

I have this service :
(function() {
'use strict';
angular
.module('myApp')
.factory('Consultant', Consultant);
Consultant.$inject = ['$resource', 'DateUtils'];
function Consultant ($resource, DateUtils) {
var resourceUrl = 'api/consultants/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
},
'update': {
method: 'PUT',
transformRequest: function (data) {
return angular.toJson(data);
},
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
},
'save': {
method: 'POST',
transformRequest: function (data) {
return angular.toJson(data);
},
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
}
})();
What if I want to add the url api/consultantscustom/:id (with its query/get/update methods) to this service?
As it seems that this file can contain only one factory, is there a way to do that or do I need to create another file with a new factory?
Maybe I am totally misunderstanding what you are asking, but you can have as many factories in one file as you like (or as seems useful):
(function() {
'use strict';
angular.module('myApp')
.factory('Consultant', Consultant)
.factory('Custom', Custom);
Consultant.$inject = ['$resource', 'DateUtils'];
Custom.$inject = ['$resource'];
function Consultant ($resource, DateUtils) {
var resourceUrl = 'api/consultants/:id';
...
}
function Custom ($resource) {
var resourceUrl = 'api/consultantscustom/:id';
...
}
Or, if you want to re-use the same factory to access different URLs, you could add methods to set the URL and then re-use the call to the generic resource.
function Consultant ($resource, DateUtils) {
function consultants () {
_call_resource('api/consultants/:id');
}
function custom () {
_call_resource('api/consultantscustom/:id');
}
function _call_resource (resourceUrl) {
return $resource(resourceUrl, {}, {
...
}
}
this.consultants = consultants;
this.custom = custom;
return this;
}

angularjs return another promise in $q.all

in my angularjs/ionic application I'm getting data from a sqlite database and want to get data from a web service which depends on the values of the database variables. I thought this might be possible with:
.factory('WebSrvs', function($http,DatabaseSrvs) {
var getData = function() {
var promiseReceiverUrl = DatabaseSrvs.getLocalValue('value1');
var promiseVehicleId = DatabaseSrvs.getLocalValue('value2');
$q.all([promiseReceiverUrl,promiseVehicleId]).then(function(results) {
if(results[0].rows.length > 0 && results[1].rows.length > 0) {
var v1 = results[0].rows.item(0).Value;
var v2 = results[1].rows.item(0).Value;
var req = {
method: 'POST',
url: v1,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: {
value: v2
},
timeout: 10000,
crossDomain: true
};
return $http(req);
}
});
}
}
But if do it this way and call it with var promise1 = WebSrvs.getData(); I don't get anything back and the app runs in a reloading queue which never ends. What am I doing wrong?
To add to my comments:
.factory('WebSrvs', function($http,DatabaseSrvs) {
var getData = function() {
var promiseReceiverUrl = DatabaseSrvs.getLocalValue('value1');
var promiseVehicleId = DatabaseSrvs.getLocalValue('value2');
return $q.all([promiseReceiverUrl,promiseVehicleId]).then(function(results) {
if(results[0].rows.length > 0 && results[1].rows.length > 0) {
var v1 = results[0].rows.item(0).Value;
var v2 = results[1].rows.item(0).Value;
var req = {
method: 'POST',
url: v1,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: {
value: v2
},
timeout: 10000,
crossDomain: true
};
return $http(req);
}
});
}
return {
getData: getData
};
}
In your factory implementation you need to first return getData function. Also inside getData function you have to return $q.all.
.factory('WebSrvs', function($http,DatabaseSrvs) {
var getData = function() {
var promiseReceiverUrl = DatabaseSrvs.getLocalValue('value1');
var promiseVehicleId = DatabaseSrvs.getLocalValue('value2');
return $q.all([promiseReceiverUrl,promiseVehicleId]).then(function(results) {
...
...
});
}
return {
getData: getData
}
}

how to create a method in service for http post in angular?

i have
$http({
url: 'http://webapi.-----UA_WebApi/GetUserAccount',
method: 'POST',
params: {Username:Username, Password:Password},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
})
and in my service i wrote this method :
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
if anyone could help me understand what i am doing (right and wrong) pls ?
i would also like an example in how to use the angular resource for post.
the PostLogin works
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
.then(function (results) {
if(results.data.TotalRows==1) {}
TotalRows is undefined when debugging. but there is TotalRows in the api
thanks
var actions = {
post: {
method: 'post',
transformResponse: function(data) {
// here is your chance to change received data
return new Model(angular.fromJson(data));
}
}
};
var url = "http://postSomeData/:id/somethingElse/:name";
var parameters = { id : 1, name : "test" }
var data = { name : "test", type : "some type" };
return $resource(url, parameters, actions).post(data).$promise;

Resources