pass Variable to Restful - javascript

my question is: How can i pass variable(java script) to a rest apllication
This one of my functions in my controller.js:
This code sampel work, but i cant use my var email and password.
at the moment i use the url path log me in(url : 'rest/ab/einloggen/t#rt.de/22'). But how can i use var email(t#rt.de) and passwort(22).
app.controller('loginCtrl', function($scope, $location,$http){
$scope.submit = function(){
var email = $scope.username;
var password = $scope.password;
$http({
method : 'GET',
url : 'rest/ab/einloggen/t#rt.de/22'
}).success(function(data, status, headers, config) {
console.log(data);
if(data=="true"){
$location.path('/eingeloggt');
console.log("lalala");
}
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
});
Here is the login rest function:
#Path("/einloggen/{username}/{passwort}")
#GET
public String einloggen(#PathParam("username") String Username,#PathParam("passwort") String Passwort)
{
// Bekomme die strings
Business b = new Business();
boolean test =b.einloggen(Username, Passwort);
//Return einer JSON
String ersatzBool ="false";
if(test==true){
ersatzBool="true";
}
return ersatzBool;
}

if you want to pass data to webapi you can use
'POST' instead of 'GET', In the below example I have passed json data {id: 2 }
and getting response as a list of products, In the api post method id 2 is available.
$http.post('http://localhost:1011/productDetails', { Id: 12 }, {
headers: {
'Content-MD5': '917200022538',
'Accept': 'application/Json',
'Content-Type': 'application/Json'
}
}).then(onUserComplete, onError);
var onUserComplete = function (response) {
$scope.Products = response.data;
};
var onError = function (reason) {
$scope.error = "Error while fetching records.";
};

This is something I had to do while communicating with a server(CMS application - Contentstack) using Restful api's, one striking difference would be I had to use authtoken.
$http({
url: siteUrl,
method: methode,
headers: {
access_token: auth_token,
api_key: site_api_key,
Accept: data_type, // --> 'application/json, text/plain, */*'
},
data: dataBody
}).then(function (resp) {
console.log('success ', resp);
callback(resp);
}, function(err){
console.log(err, "error");
});

Related

Run HTTP post on successful post login

I have a simple login, once user is logged in I have added a call back to run another post so that I have access to the post json to use in my system.
I think the way I have done it is correct however I am getting error
GetData is not defined
Is this the correct way to do this
JavaScript
$scope.LogIn = function () {
$http({
url: "http://www.somesite.co.uk/ccuploader/users/login",
method: "POST",
data: $.param({'username': $scope.UserName, 'password': $scope.PassWord}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
GetData();
// location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
$scope.UserData = function ($scope) {
$scope.UserName = "";
$scope.PassWord = "";
};
$scope.GetData = function () {
$http({
url: " http://www.somesite.co.uk/ccuploader/campaigns/getCampaign",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log("then : " + JSON.stringify(response));
location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
You need to update your code to be $scope.GetData();.
Currently you are using GetData() which doesn't reference the same method. In fact it is undefined as per the error message.

in angular js, how to store variable for use in other http functions

I have the following controller:
angular.
module('phoneList').
component('phoneList', {
templateUrl: '/phone-list.template.html',
controller: ['$http',
function PhoneListController($http) {
var self = this;
var access_token = '';
var data = $.param({
grant_type: 'password',
username: 'test',
password: 'test',
client_id:'1234',
client_secret:'12345',
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('/o/token/', data, config)
.success(function (data, status, headers, config) {
self.access_token = data['access_token'];
console.log(access_token);
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
var header = {
headers : {
'Authorization': 'Bearer '+self.access_token
}
}
$http({method: 'GET', url: 'api/posts/', headers: {'Authorization': 'Bearer '+self.access_token}}).then(function(response) {
self.phones = response.data;
});
}
]
});
I want to use the access token returned from this function that lasts several days. I don't want to get a new token every time but determine if the token is expired or if another needs to be retrieved:
$http.post('/o/token/', data, config)
.success(function (data, status, headers, config) {
self.access_token = data['access_token'];
console.log(access_token);
})
In my get function:
$http({method: 'GET', url: 'api/posts/', headers: {'Authorization': 'Bearer '+self.access_token}}).then(function(response) {
self.phones = response.data;
});
How do I accomplish this?
Let's say your app's name is myapp.
Then, create a module called authentication where you can put a factory that will retrieve the token and put it in a session storage. In the same factory, you can add a getToken service that will return your session storage data :
angular.module('authentication').factory('authenticationService', function($http, $se){
function authenticate(){
$http.post('/o/token/', data, config)
.success(function (data, status, headers, config) {
$sessionStorage.access_token = data['access_token'];
});
}
function getToken(){
return $sessionStorage.access_token;
}
return {
authenticate:authenticate,
getToken:getToken
};
});
In your main module, call the the run function and invoke your service :
angular.module('myapp').run(function(authenticationService){
authenticationService.authenticate().then(function(){
// Redirection to the next route
});
});
In your controller, just inject the authenticationService factory and retrieve the token with the authenticationService.getToken() instead of doing Ajax calls :
$http({method: 'GET', url: 'api/posts/', headers: {'Authorization': 'Bearer '+ authenticationService.getToken()}}).then(function(response) {
self.phones = response.data;
});

AngularJS http return value

I want to write a function in AngularJS that returns a value (actually it is a string). That value is returned by a http request, but async is driving me crazy.
My first attempt was:
this.readParameter = function(key) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
throw new Error("Error");
})
};
But of course it does not work because of Angular async features (response.data is undefined)
What is the way to do it? I just want to return the value (string), so I can use this function like
var a = readParameter("key1")
What you can do is define some variable with initial value outside function and on response set value inside success function instead of returning it.
Delegator pattern works great here to assign $http task to some service and use callback method for response.
Controller (Call Service for specific request) -> Service (Manage request params and other things and return factory response to Controller) -> Factory (Send request and return it to Service)
Basic example of Callback
var myVariable = '';
function myFunction (key, callback) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
callback(response);
}, function errorCallback(response) {
throw new Error("Error");
})
};
function myCallbackFunction(response) {
myVariable = response.data; // assign value to variable
// Do some work after getting response
}
myFunction('MY_KEY', myCallbackFunction);
This is basic example to set value but instead use callback pattern from above example.
var myvariable = '';
function myFunction (key) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
myvariable = response.data; // set data to myvariable
// Do something else on success response
}, function errorCallback(response) {
throw new Error("Error");
})
};
myFunction('MY_KEY');
Don't try to mix async and sync programming. Instead use a callback to use like
readParameter("key1", callback)
for example:
this.readParameter = function(key, callback) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
callback(response)
}, function errorCallback(response) {
throw new Error("Error");
})
};
I resolve this by using promise:
Example :
in Service (invoicesAPIservice => invoicesapiservice.js) you use:
angular.module('app')
.service('invoicesAPIservice', function ($http) {
this.connectToAPI= function () {
return new Promise(function(resolve,reject){
var options = {
method:'GET',
url :'',
headers:{
'X-User-Agent': '....',
'Authorization': '....',
}
};
$http(options).then(function successCallback(response) {
resolve(response);
//console.log(response);
},function errorCallback(response) {
reject(response);
})
});
});
});
and in your Controller (mainCtrl=> mainCtrl.js):
angular.module('app').controller('mainCtrl', function($scope,invoicesAPIservice) {
$scope.connectToAPI=function () {
invoicesAPIservice.connectToAPI().then(function (content) {
console.log(content.statusText);
}.catch(function (err) {
//console.log(err);
alert("Server is Out");
});
}
});
And in your page : index.html:
<button ng-click="connectToAPI()"></button>
:)

Parse webrequest to Coinbase gives 401 not authorized

I'm trying to send bitcoin through Coinbase's API, and this is my code:
// create object to send as data
var transaction = {
to : correctusermail, // "my#email.com"
amount_string : amount, // "1.00"
amount_currency_iso : currency // "EUR"
};
// get correct auth key from user
var authq = new Parse.Query(Parse.User);
authq.get(objectid, {
success: function(userObject) {
correctauth = userObject.get("provider_access_token");
console.log(correctauth);
console.log(transaction);
// send post request
// make post request
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
access_token: correctauth,
transaction: transaction
},
success: function(httpResponse) {
response.success(120);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(111);
}
});
},
error: function(userObject, error) {
response.error(150);
}
});
As you can see I'm making sure that my correctauth var is correct by logging it, which works just fine.
All the other variables are correct, I've checked them. So what am I missing? It's probably very small.
From my understanding of the Coinbase API documentation, the access_token should always be part of the URL, e.g.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money?access_token='
+ correctauth,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
transaction: transaction
},
// ... etc ...

Angular JS AJAX Call with Parameters

without the parameters of the method Get, the code works, but if the method asks for a parameter an error 404 is returned. How do I properly send parameters with Angular JS?
factory.test = function () {
var q = $q.defer();
$http({
method: "GET",
url: url + "/dataEntry/test",
data: {
sampletext : "sample"
}
})
.success(function (data, status, headers, config) {
q.resolve(data);
})
.error(function (data, status, headers, config) {
q.reject(data);
});
return q.promise;
};
[Route("test")]
public String Get(string sampletext)
{
return "Reply coming from data entry controller" + sampletext;
}
Since it's a GET request you shouldn't be sending data. You need to be sending a query string.
Change your data to params.
$http({
method: "GET",
url: url + "/dataEntry/test",
params: {
sampletext : "sample"
}
})
Source: http://docs.angularjs.org/api/ng/service/$http
$http({
url: "/saveInfo",
method: 'Post'
}).then(function(response) {
console.log("saved successfully");
}, function(response) {
console.log("Error message");
});

Categories