I have created two common services for my all master modules. One using ng-resource.
app.service('CRUDService',function($resource, $window){
var data = JSON.parse($window.localStorage["userInfo"]);
this.crudFunction = function (url) {
return $resource(url , {id:'#_id'},{
update: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept' : 'application/json',
'Authorization' : 'Bearer '+data['accessToken']
}
},
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept' : 'application/json',
'Authorization' : 'Bearer '+data['accessToken']
}
},
remove: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept' : 'application/json',
'Authorization' : 'Bearer '+data['accessToken']
}
},
get :{
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept' : 'application/json',
'Authorization' : 'Bearer '+data['accessToken']
}
}
});
}
});
And another service for common functions used by all controllers.
app.service('commonService', function (CRUDService) {
var vm = this;
var resourceUrl = apiUrl;
vm.totalItemsTemp = {};
vm.totalItems = 0;
vm.currentPage = 1;
vm.pageChanged = function(newPage) {
getResultsPage(newPage);
};
vm.load = function(url) {
resourceUrl = url;
getResultsPage(1);
}
function getResultsPage(pageNumber) {
CRUDService.crudFunction(resourceUrl).get({"page": pageNumber},function success(response) {
vm.listdata = response["data"];
vm.totalItems = response.total;
vm.currentPage = pageNumber;
},
function error(response) {
console.log(response);
});
}
vm.save = function() {
CRUDService.crudFunction(resourceUrl).save($.param(vm.newEntry),function(response) {
if(response["success"] == true)
{
vm.listdata.push(response["inserted_data"]);
getResultsPage(vm.currentPage);
$(".modal").modal('hide');
}
else
vm.msg = "Error Saving";
},function(response) {
vm.error = response['data'];
});
}
vm.create = function(){
vm.newEntry = {};
vm.editData = 0;
vm.error = {};
}
vm.edit = function(id,index) {
vm.newEntry = angular.copy(vm.listdata[index]);
vm.editData = 1;
vm.edit_index = index;
vm.error = {};
}
vm.update = function(id,index) {
vm.newEntry._method = "PUT";
CRUDService.crudFunction(resourceUrl).update({id : id} , $.param(vm.newEntry),function(response) {
if(response["success"] == true)
{
vm.listdata[index] = response["updated_data"];
$(".modal").modal('hide');
vm.newEntry = {};
}
else
vm.msg = "Error Updating";
},function(response) {
vm.error = response['data'];
});
}
vm.remove = function(id, index) {
var result = confirm("Are you sure you want to delete vm?");
if (result) {
CRUDService.crudFunction(resourceUrl).remove({id : id} , $.param({"_method" : "DELETE"}),function(response) {
getResultsPage(vm.currentPage);
},function(response) {
console.log(response);
});
}
}
});
And I am injecting commonService in my controller like this:
app.controller('UserRolesCtrl', function($scope, commonService) {
commonService.load(apiUrl + 'roles/:id');
$scope.userroles = commonService;
});
app.controller('SupportMembersCtrl', function($scope, commonService) {
commonService.load(apiUrl + 'supportmembers/:id');
$scope.supportmembers = commonService;
});
Now I am using tabs for each module. So that my all controllers will be in same page. But all the tabs showing same data. Is it because both controllers are using same variable names? But both the controller's references are different.
Is it because both controllers are using same variable names?
No. Each controller has his own scope so you can create variables with the same name
But both the controller's references are different.
The service is like singleton and you do 2 calls:
commonService.load(apiUrl + 'supportmembers/:id');
commonService.load(apiUrl + 'roles/:id');
The 1st problem is in method: run
you override resourceUrl twice
vm.load = function(url) {
resourceUrl = url; // <-- here
getResultsPage(1);
}
The 2nd problem - you store results under the same variables in service
vm.listdata = response["data"];
vm.totalItems = response.total;
vm.currentPage = pageNumber;
The one of solutions is to store data in map under unique key, in your case you can take your URL. Something like:
vm.load = function(url) {
//resourceUrl = url;
getResultsPage(1, url); // pass url as argument
}
function getResultsPage(pageNumber, url) {
CRUDService.crudFunction(url).get({"page": pageNumber},function success(response) {
// ...
},
function error(response) {
console.log(response);
});
}
Angularjs' services are singletons and you are injecting reference to the same service. Try to not assign results into
vm.listdata = response["data"];
vm.totalItems = response.total;
vm.currentPage = pageNumber;
But return it directly. Both methods saves results under the same properties od singleton. So only last result is available. I think so:)
Related
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)
This is my controller.
sampleApp.controller('SupplierController', ['$scope', '$http', 'SupplierService', function ($scope, $http, SupplierService){
$scope.Suppliers = [];
$scope.getSuppliers = function() {
SupplierService.getSuppliers().then(function(data) {
$scope.Suppliers = data;
});
};
$scope.editSupplier = function(supplier) {
SupplierService.editSupplier(supplier);
editMode = false;
};
$scope.getSuppliers();
}]);
This is my service.
sampleApp.factory('SupplierService', function($http, $q) {
var SupplierService = {};
var SupplierList = [];
SupplierService.getSuppliers = function() {
var Info = {};
Info.Action = "GET";
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
if ( SupplierList.length === 0 )
{
return $http(req).then(function (response) {
SupplierList = response.data
return response.data;
});
}
else
{
var deferred = $q.defer();
deferred.resolve(SupplierList);
return deferred.promise;
}
};
SupplierService.addNewSupplier = function(supplier) {
var Info = {};
Info.Action = "ADD";
Info.SupplierName = supplier.name;
Info.SupplierMobile = supplier.mobile;
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
$http(req)
.success(function(data) {
alert ('Supplier update is successful.');
})
.error(function (data, status, headers, config) {
alert ('Supplier update error.');
});
};
SupplierService.editSupplier = function(supplier) {
var Info = {};
Info.Action = "UPDATE";
Info.SupplierID = supplier.id;
Info.SupplierName = supplier.name;
Info.SupplierMobile = supplier.mobile;
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
$http(req)
.success(function(data) {
alert ('Supplier update is successful.');
})
.error(function (data, status, headers, config) {
alert ('Supplier update error.');
});
};
return SupplierService;
});
What i want is, only when http call for editSupplier is successful then only i want this line to be executed.
editMode = false;
Currently above line is in $scope.editSupplier function. so irrespective of success or failure it is getting called. How to move this line to service??
Any better approach will be highly appreciated.
The easiest way, based on your current setup, would be to return $http(req) (as that is a promise). So the end of editSupplier would say:
return $http(req);
And in your controller, you could do:
SupplierService.editSupplier(supplier).success(function(response) {
editMode = false;
});
You could additionally chain the .error handler if you have something specific to do in the case of an error.
#tandrewnichols stole my initial answer so I'll offer the alternative.:p
Move editMode into the service and use a getter to check the value of editMode.
Also, are you intending to make editMode a global variable in your application?
I'm trying to create a chat app where you can log into the incontact chat api (discard the weatherApp naming.. ).
This is the API documentation for the incontact chat api:
function startAgentSession() {
var startSessionPayload = {
'stationId': 'string',
'stationPhoneNumber': 'string',
'inactivityTimeout': 'integer - 30-300, or 0 for default',
'inactivityForceLogout': 'boolean',
'asAgentId': 'integer'
}
$.ajax({
//The baseURI variable is created by the result.base_server_base_uri
//which is returned when getting a token and should be used to create the URL base
'url': baseURI + 'services/{version}/agent-sessions',
'type': 'POST',
'headers': {
//Use access_token previously retrieved from inContact token service
'Authorization': 'bearer ' + accessToken,
'content-Type': 'application/json'
},
'data': JSON.stringify(startSessionPayload),
'success': function (result) {
//Process success actions
return result;
},
'error': function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
return false;
}
});
``}
This is my attempt to convert in angular js, but for some reason I keep getting a 404, however, I'm at a loss for what I've done wrong..
weatherApp.controller('launchedController', ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.clientResult = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '55555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}).success(function(data) {
$scope.data = data;
consoloe.log('data', $scope.data)
}).error(function(status) {
$scope.status = status;
});
}]);
400 error is bad request. My guess is
replace
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}
with
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: $scope.startSessionPayload
}
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
}
}
I have two api one is for login and another is for logout, and on succcessfulll login I am getting the acesstoken and on the basis of acesstoken I have to logout by passing the that acesstoken in header.
So for logout what I did, I stored that acesstoken value in localstorage and pass in the header but I am getting error "AccessToken is invalid."
Here is services.js:
angular.module('server', [])
.factory('api', function($http) {
var token = localStorage.AccessToken;
console.log(token);
var server = "http://myapi-nethealth.azurewebsites.net";
return {
//Login
login : function(formdata) {
return $http({
method: 'POST',
url: server + '/Users/Login',
data: $.param(formdata),
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
});
},
logout : function() {
return $http({
method: 'POST',
url: server + '/Users/Me/Logout',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded', 'Authorization' : 'token ' + token},
/*headers: { 'Content-Type' : 'application/json', 'Authorization' : 'token ' + token},*/
}).success(function (data, status, headers, config){
alert(JSON.stringify(status));
});
}
};
});
//Controller.js..
ctrl.controller('logout', function($scope, $window, $state, api) {
$scope.logout = function() {
api.logout()
.success(function(data) {
console.log(data);
$scope.response = data;
$state.go('home');
})
.error(function(data) {
console.log(data);
$scope.response = data;
});
}
});
ctrl.controller('search', function($scope, $state) {
$scope.search = function() {
$state.go('clinic-list');
};
});
ctrl.controller('clinicCtrl', function($scope, $state, $window, api) {
$scope.formData = {};
$scope.clinicCtrl = function() {
/*$scope.loading = true;*/
api.login($scope.formData)
.success(function(data, status) {
console.log(data);
$scope.response = data;
if (data.hasOwnProperty('AccessToken') && data.AccessToken.length > 5) {
$state.go('home');
window.localStorage['AccessToken'] = angular.toJson(data.AccessToken);
var accessData = window.localStorage['AccessToken'];
console.log(accessData);
} else {
$state.go('login');
}
/*$scope.loading = false;*/
})
.error(function(data) {
console.log(data);
$scope.response = data;
$window.alert($scope.response.Message);
console.log($scope.response.Message);
});
}
});
Please tell me how can I do this....
angular.module('server', []).factory('authInterceptor',function($q,$location) {
return {
request: function(config) {
config.headers = config.headers || {};
if(localStorage.AccessToken) {
config.headers.AccessToken = localStorage.AccessToken;
}
config.headers.requestResourse = $location.$$url;
return config;
},
responseError: function(response) {
return $q.reject(response);
}
}
}).config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
})..factory('api', function($http) {
var token = localStorage.AccessToken;
console.log(token);
var server = "http://myapi-nethealth.azurewebsites.net";
return {
//Login
login : function(formdata) {
return $http({
method: 'POST',
url: server + '/Users/Login',
data: $.param(formdata),
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
});
},...............
this will append the token to all the requests, after u getting the reponse, in the controller you can re set the token :)
customize according to your variables