AngularJS requests duplicate - javascript

I use AngularJS for my application to send multiple requests to the server. Here is an example of my code
HTML
<body ng-controller="AccessCtrl">
Javascript
mainApp.factory('authService', function ($rootScope, $http) {
return {
access: function () {
$http({
method: 'POST',
url: some_url,
data: 'grant_type=client_credentials',
}).success(function (response) {
console.log(response);
$rootScope.access_token = response.access_token;
});
}
}
});
controllersApp.controller('AccessCtrl', ['FactoryModule', function (FactoryModule) {
var testServices = FactoryModule('services');
testServices.authService.access();
}]);
And here is my console:
enter image description here
I have 2 requests from index and from angular initiators. How to fix this? I want 1 request to get access token.

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();
}]);

In Angular JS $scope variable value assign from $http

I'm new to angular js. Here i have the code: I receive the response data like number. In this code how i assign the response data as $scope.vote_counting. In this code does not return anything.
$scope.votes = function(){
var votes = $http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id}
}).success(function(response){
});
return votes;
}
Please anyone help to this.
Simply call the $http. It does not have to be in a function
$http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id }
}).then(function(response) {
//handle success
$scope.votes_counting = response.data;
}, function(error){
//handle error
});
The sort version is
$http.post("/getVotes", { id: $scope.Id }).then(function(response) {
//handle success
$scope.votes_counting = response.data;
}, function(error) {
//handle error
})
Note : You are using a POST method but a GET method seems more appropriate in your case (getVotes)
I've added a snippet, which shows the basic handling of promises. Here, I've used a service to mock a http call. The response is attached to a scope variable, which is presented in the view.
angular.module('TestApp', [])
.factory('MockHttp', function($q) {
return {
getMockData: function() {
return $q.when(['A', 'B', 'C']);
}
};
})
.controller('TestController', function($scope, MockHttp) {
$scope.res = null;
MockHttp.getMockData()
.then(function(res)  {
$scope.res = res;
})
.catch(function(err) {
console.log(err);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp">
<div ng-controller="TestController">
{{res}}
</div>
</div>
The $http function does not return the response of the server. But as you have already figured out you can use the success function to get the servers response. Simply set $scope.votes value in the success function like this:
$http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id}
}).success(function(response){
$scope.votes = response
});
The easiest is probably using $http.post. Note that success is deprecated in favour of then:
$scope.retrieveVotes = function(){
$http.post('/getVotes', {id : $scope.id}).then(function(response){
$scope.votes = response.data;
});
}
Also note that $http calls are asynchronous so calling retrieveVotes is also asynchronous.

Consuming a restful service with 'slash' char in uri parameter in angular JS

I have a situation where I need to consume a restful web service in AngularJS using GET method by allowing it to accept slash "/" character in uri parameter.
Normally "/" slash, creates a different end point and service doesn't give the required response and I need to consume the RESTful web service where the parameter should be passed as string.
Scenario to be considered:
Sample URL: http://hostname/servicename/{parameter}
where parameter should be a string and Should be valid for below sample inputs
a
12
12/15
126/567
I am using below code
service.js
angular.module('starter.services', [])
.factory('dataService', ['$http', function($http) {
var obj = {};
obj.getData = function(url){
return $http({
method: 'GET',
url: url,
headers: {'Content-Type': 'application/json;charset=utf-8'},
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return "ERROR";
});
}
return obj;
}])
controller.js
var url = "http://hostname/servicename/" + paramId + "";
dataService.getData(url).then(
function(response) {
// Response stuff here
}
)
NOTE: I have to manage all things at client side and don't have access to server side code of web service.
Encode the parameter like this.
encodeURIComponent(paramId)
Otherwise replace / with '%2f'
Have u tried params object instead passing the parameter directly in the url?
If no.. just pass the parameter as shown below.
service.js
angular.module('starter.services', [])
.factory('dataService', ['$http', function($http) {
var obj = {};
obj.getData = function(url, paramId){
return $http({
method: 'GET',
url: url,
params:{
"paramId" : paramId
},
headers: {'Content-Type': 'application/json;charset=utf-8'},
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return "ERROR";
});
}
return obj;
}]);
controller.js
var url = "http://hostname/servicename";
dataService.getData(url, paramId).then(
function(response) {
// Response stuff here
}
);
Let me know if this helps!

Problems when passing parameters of an Angular application for a Rails controller

I have an application made in angularjs, but I'm having trouble reading the parameters on the server side.
As I'm sending the data:
api.factory('AuthProvider', function($resource, ENV){
var baseUrl = ENV.apiEndpoint;
return $resource(baseUrl, null,
{
login: {
method: 'POST',
url: baseUrl+'sessions'
}
});
});
angular.module('tuneduc.controllers.admin',[])
.controller('AdminController', function($scope, $location, AuthProvider) {
var auth;
$scope.login = function (credentials) {
auth = new AuthProvider(credentials)
auth.$login(function(res) {
console.log('success');
},
function(res) {
console.log(res.data.errors);
})
}
});
So the parameters are coming this way on the server:
{"{\"email\":\"assdaf#adfasdf.com\",\"password\":\"sadfsdf\"}"=>nil, "controller"=>"sessions", "action"=>"create"}
I've tried using JSON.stringify () but failed.

Categories

Resources