Angularjs: Singleton service using $http [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
is it possible in angular to create service using $http which will take method, url, success and failure callback as parameters when called from controller.
I want to achieve following kind of functionality using angular.
var ajax = {
URL: "webservice url",
loggedIn: false,
importedId: "",
token: '',
userdetails: new Backbone.Collection.extend({}),
serverCall: function(method, data, successCallBack, failureCallBack) {
var that = this;
//console.log(method);
//console.log(successCallBack);
that.showLoading();
$.ajax({
url: that.URL + method,
method: 'post',
data: data,
// contentType:"application/json; charset=utf-8",
success: function(data) {
that.hideLoading();
if (that.checkForError(data))
{
successCallBack(data);
}
},
fail: function(data) {
that.hideLoading();
failureCallBack(data);
}
});
}
i am using https://github.com/StarterSquad/startersquad.github.com/tree/master/examples/angularjs-requirejs-2 folder structure for app and inside services i have following code
define(['./module'], function(services) {
'use strict';
services.factory('user_resources', ['$resource', '$location', function($resource, $location) {
return $resource("", {},
{
'getAll': {method: "GET", url:'JSON/myList.JSON',isArray:true}
});
}]);
});
and in controller i have following code
define(['./module'], function (controllers) {
'use strict';
controllers.controller('myListCtrl',['Phone','Phone1','loginForm','$scope','$http','user_resources','CreditCard',function(Phone,Phone1,loginForm,$scope,$http,user_resources,CreditCard){
console.log(user_resources.getAll())
}]);
});
which returns [$promise: Object, $resolved: false] how to get data from that?

A service in AngularJS is always a singleton, so you wouldn't have to do anything to achieve that. However, it seems like you do not actually want a singleton as you want to pass in different values. Thus, you might want to add your own service factory function. Something like:
function MyHTTPService($rootScope, url, method) {
this.$rootScope = $rootScope;
this.url = URL;
this.method = method;
}
MyHTTPService.prototype.serverCall = function () {
// do server call, using $http and your URL and Method
};
App.factory('MyHTTPService', function ($injector) {
return function(url, method) {
return $injector.instantiate(MyHTTPService,{ url: url, method: method });
};
});
This can be called using
new MyHTTPService("http://my.url.com", "GET");

you could also use $resource for this type of usage.
angular.module('MyApp.services').
factory('User_Resource',["$resource","$location", function ($resource,$location){
var baseUrl = $location.protocol() + "://" + $location.host() + ($location.port() && ":" + $location.port()) + "/";
return $resource(baseUrl+'rest/users/beforebar/:id',{}, {
query: { method: 'GET', isArray: true },
get: { method: 'GET' },
login: { method: 'POST', url:baseUrl+'rest/users/login'},
loginAnonymous: { method: 'POST', url:baseUrl+'rest/users/loginAnonymous'},
logout: { method: 'POST', url:baseUrl+'rest/users/logout/:id'},
register: { method: 'POST', url:baseUrl+'rest/users/register'}
});
}]);
Example of usage :
userSrv.logout = function(user,successFunction,errorFunction)
{
var userSrv = new User_Resource();
userSrv.$logout({user.id}, //params
function (data) { //success
console.log("User.logout - received");
console.log(data);
if (successFunction !=undefined)
successFunction(data);
},
function (data) { //failure
//error handling goes here
console.log("User.logout - error received");
console.log(data);
var errorMessage = "Connexion error";
if (errorFunction !=undefined)
errorFunction(errorMessage);
});
}

Related

Problem inizialise a global variable AngularJS by calling a REST service

I want to create a global variable (httpTimeout) initialize at the start, contains a Long value returned by a synchrone call Rest Service and used it in different service
(
function () {
'use strict';
angular
.module('module')
.factory('MyService', function (
$http,
$q
){
var service = {};
var httpTimeout = function() {
return $http({
method: 'GET', '.../rest/getHttpTimeOut'
}).then(function (response) {
return response.data;
}).catch(function (err) {
return 30000;
});
};
service.myService1= function (Model) {
return $http({
method: 'POST', '..../rest/callRestService1',
data: Model, timeout : httpTimeout
}).then(function (response) {
return response.data;
});
};
service.myService2= function (Model) {
return $http({
method: 'POST', '..../rest/callRestService2',
data: Model, timeout : httpTimeout
}).then(function (response) {
return response.data;
});
};});
My rest service
#RequestMapping(value = "/getHttpTimeOut", method = RequestMethod.GET)
#ResponseBody
public long getHttpTimeOutValue() {
return timeoutValue;
}
how i can retrieve this value globally (httpTimeout) for use in other services
Thank you for your help
if your question is how to do something on application start :
look at that
After your application start you can use another service to store the value.
Also if you want to apply this comportement for all request take a look to interceptor

Convert JS Post Ajax to AngularJS Post Factory

I am trying to convert an Ajax call with WSSE authentication to an AngularJS factory.
The method is Post.
The intended use of this is to access the Adobe Analytics Rest API and return data to be converted to JSON and then visualised with d3.js.
I am not familiar with the properties that can be used in an AngularJS $http post call and so not sure what is the correct way to do the WSSE auth, dataType, callback etc.
This is the original ajax code which came from a public github repo:
(function($) {
window.MarketingCloud = {
env: {},
wsse: new Wsse(),
/** Make the api request */
/* callback should follow standard jQuery request format:
* function callback(data)
*/
makeRequest: function (username, secret, method, params, endpoint, callback)
{
var headers = MarketingCloud.wsse.generateAuth(username, secret);
var url = 'https://'+endpoint+'/admin/1.4/rest/?method='+method;
$.ajax(url, {
type:'POST',
data: params,
complete: callback,
dataType: "text",
headers: {
'X-WSSE': headers['X-WSSE']
}
});
}
};
})(jQuery);
This is the current way the code is being used with pure JS:
MarketingCloud.makeRequest(username, secret, method, params, endpoint, function(response) {
data = JSON.parse(response.responseText);
});
I want to convert this to a factory and a controller respectively.
This is what I have done for the factory so far:
app.factory('mainFactory', ['$http', function($http) {
var wsse = new Wsse ();
return function(username, secret, method, params, endpoint) {
return $http({
method: 'POST',
url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
data: params,
headers: {
'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
},
dataType: 'text',
});
};
}]);
And this is what I have for the controller:
app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
mainFactory.success(function(data) {
$scope.data = data;
});
}]);
Currently I get an error saying mainFactory.success is not a function which I assume is because the factory isn't working yet.
I have resolved this question myself. The parameters I was passing to the first function in the factory were globally defined already and therefore getting over-written.
The first function is not required anyway.
Here is the factory code:
app.factory('mainFactory', ['$http', function($http) {
var wsse = new Wsse ();
return {
getAnalytics : function (){
$http({
method: 'POST',
url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
data: params,
headers: {
'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
}
})
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
};
}]);
And here is the controller code:
app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
$scope.title = "Inn Site";
$scope.data = mainFactory.getAnalytics();
}]);

How to change location and refresh page in angular js

I have a function :
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
return response.data;
});
}
and the function work perfectly, but i want my page change to datalist and refresh datalist after insert() true. my function insert() run in the route "localhost/learn/#!/administrator" so i want it change to route "localhost/learn/#!/" after insert() true. i used location.href='#!/' but it not work for refresh datalist automaticaly, just change location.
If you want to update an object from a service call, you can do the following. I have added an onError function too, to help with debugging.
Tip: Research adding service calls into a Service that AngularJS framework provides. It helps for writing maintainable and structured code.
$scope.objectToUpdate;
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
$scope.objectToUpdate = response.data.d;
}, function(e){
alert(e); //catch error
});
}
Optional Service
Below is an example of how to make use of Angular Services to make server calls
app.service('dataService', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function (url, data) {
// $http() returns a $promise that we can add handlers with .then() in controller
return $http({
method: 'POST',
url: './sys/' + url + '.php',
dataType: 'json',
data: data,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
};
});
Then call this service from your controller, or any controller that injects DataService
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
dataService.getData('mac', data).then(function (e) {
$scope.objectToUpdate = e.data.d;
}, function (error) {
alert(error);
});

Passing complex object from angular js factory to web api using $resource

I am passing an object to angular factory it is throwing error.
factory:
visitorApp.factory('loginRepository', function ($resource) {
return {
VerifyVisitor: $resource('/api/VisitorWeb/VerifyLogin', {}, {
query: { method: 'POST', params: {loginModel:loginModel}, isArray: true }
})
};
});
The complex object i am trying to pass is loginModel.
From controller call to factory.
visitorApp.controller('LoginController', function ($scope,$location,$route,loginRepository) {
$scope.submit = function (isValid) {
if (isValid) {
var loginModel = {
UserName: $scope.UserName,
PassWord: $scope.Password
};
var response = loginRepository.VerifyVisitor.query(loginModel);
alert(response);
}
}
});
Error: loginModel is not defined
Web Api Method which is being called.
[HttpPost]
public string VerifyLogin(UserLoginDomainModel loginModel)
{
var msg = _loginService.Login(loginModel);
return msg;
}
Is it the right way of using $resource to post a request and pass complex object.
Your service should look something like this:
visitorApp.factory('loginRepository', function ($resource) {
return {
VerifyVisitor: $resource('/api/VisitorWeb/VerifyLogin', {},
{
query: {
method: 'POST',
params: {loginModel: '#loginModel'},
isArray: true }
})
};
});
The parameter variables are enclosed in quotes and prefixed with an #.

Angular promise after calling a service with $http

I m actually developping an application with angularjs, and I m facing a problem with $http, and the result of an asynchronous service request to my webservice.
Actually, I m using this code :
var promise = undefined;
UserService.getAll = function (callback) {
promise = $http({
url: __ADRS_SRV__ + "users",
method: "GET",
isArray: true
}).success(function(data){
return data;
}).error(function(data){
return $q.reject(data);
});
return promise;
}
This doesnt work, and give me some stuff like, I dont know why :
To know : in my controller, I want to use a really simple syntax like
var data = UserService.getAll();
Do you have any idea how should I process to access my data correctly ?
Thanks for advance
you get the promise in return. There are multiple ways to use this promise.
Example 1 (Use promise in service and return reference of an object):
UserService.getAll = function () {
var dataWrapper = {
myData: {},
error: null
};
$http({
url: __ADRS_SRV__ + "users",
method: "GET",
isArray: true
}).success(function(data){
dataWrapper.myData = data;
}).error(function(data){
dataWrapper.error = true;
return $q.reject(data);
});
return dataWrapper;
}
Example 2 (Return promise and use it directly in the controller):
// service
UserService.getAll = function () {
return $http({
url: __ADRS_SRV__ + "users",
method: "GET",
isArray: true
});
}
// controller
var promise = UserService.getAll();
promise.success(function(data) {
$scope.data = data;
});
Example 3 (Use regular callback):
// service
UserService.getAll = function (cb) {
$http({
url: __ADRS_SRV__ + "users",
method: "GET",
isArray: true
}).success(cb);
}
// controller
UserService.getAll(function(data) {
$scope.data = data;
});
The "stuff" you mention is the very promise you create and return.

Categories

Resources