Create a function with angularJS - angularjs

I am very new on the forum and also with AngularJS.
I am trying to send a request to a REST server. I used this function
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
params: {
name: 'test'
}
});
request.success(
function() {
//alert('it succeeded');
}
);
request.error(
function() {
// alert('it didnt work');
}
);
};
The code is not working properly on the server side because of some serialization stuff. I found a post on the forum that suggests using this function instead
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
username: $scope.userName,
password: $scope.password
}
}).success(function() {});
I am not sure how to use this function with my code, I tried this code
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
name: 'test'
}
}).success(function() {});
but I get an error due to the }); . Can someone help me to format and fix the code?

$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {name: 'test'}}).success(function () {});
} // you need a '}' here.
also you can try the post method of $http this way.
$http.post('url', data)
.success(function(data, status, headers) { //success callback })
.error(function(data, status, headers) { //error callback });

Related

Angularjs parsses non JSON POST response

I send a POST request to a server. As response the server send a http code and a plain text.
return Response.status(200).entity("Started").build();
AngularJS try to parse the response to json and I get a parsing error
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON
data
This is my Angular code
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/server/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
data: {name: $scope.name}}).then(function(html) {
//success callback code
//console.log(html)
}, function(html) {
//error callback code
//console.log(html)
});
}
You need to override transform response function
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/server/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
transformResponse: [
function (data) {
return data;
},
],
data: {name: $scope.name}}).then(function(html) {
//success callback code
//console.log(html)
}, function(html) {
//error callback code
//console.log(html)
});
}

Converting ajax api post to $http post in angular js getting a 404

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
}

AngularJS factory undefined error

I am stuck here, I don't know what I am missing or how to debug this further. I continue to get this error: 'updateMemberServiceFactory is undefined' when I call it from an ng-click event. Please advise. If this is a simple typo I apologize I just can't see what's wrong. I'm trying to call into a PUT method on my controller but it never gets called. New to AngularJS. Thank you.
securityApp.factory('updateMemberServiceFactory', function ($http) {
function update(memberServiceID) {
$http({ method: 'PUT', url: 'http://localhost:62791/api/MemberServices/', data: { memberServiceID: memberServiceID } })
.then(function (result) {
alert('success');
}, function (errorResponse) {
});
};
});
securityApp.controller('memberServicesController', function ($scope, $http, $routeParams, $location, getTokenFromServer, updateMemberServiceFactory) {
var id = $routeParams.memberID;
$scope.username = 'aharris1#test.com';
$scope.password = 'SuperPass1!';
getTokenFromServer.getToken($scope.username, $scope.password).then(function (data) {
$scope.token = data;
$http({ method: 'GET', url: '/api/MemberServices/' + id + '?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.success(function (response) {
$scope.memberServices = "";
$scope.memberServices = response;
$http({ method: 'GET', url: '/api/Members/' + id + '?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.success(function (response) {
$scope.member = response;
});
$http.get('/api/ServiceTypes/')
.then(function (response) {
$scope.serviceTypes = response.data;
});
});
});
$scope.updateMemberService = function () {
updateMemberServiceFactory.update( { memberServiceID: memberServiceID }, null, function () {
alert('update called');
});
};
});
<i class="fa fa-save"></i>
When you use someApp.factory(someFunction) the some someFunction should return an object that will be injected when needed.
In your case:
securityApp.factory('updateMemberServiceFactory', function ($http) {
function update(memberServiceID) {
$http({ method: 'PUT', url: 'http://localhost:62791/api/MemberServices/', data: { memberServiceID: memberServiceID } })
.then(function (result) {
alert('success');
}, function (errorResponse) {
});
};
return { // <---- this object will get injected, when required
update : update
}
});

Angular Factory to share web api 2 token with multiple controllers

I am trying to create a factory that gets a token from a web api and then shares that token with multiple controllers. I've tried my best to create the factory and inject it into the controller but I am not sure if I am doing this correctly yet? I'm getting an angular 'unknown provider' error. Please advise, new to angular. Thank you.
securityApp.factory('getToken', function ($scope, $http) {
var token = "";
$http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: $scope.userName, password: $scope.password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).success(function (data, status, headers, config) {
token = data.access_token;
return token;
});
});
securityApp.controller('membersController', function ($scope, $http, getToken) {
$http({ method: 'GET', url: '/api/Members/?access_token=' + getToken.token, headers: { 'Authorization': 'Bearer ' + getToken.token } })
.then(function (response) {
$scope.members = response.data;
});
});
A service can't be injected with $scope. Only controllers can. The only scope that can be injected in a service is the $rootScope. You need to pass the user name and the password to your service when calling it. It can't bet the user name and password from nowhere.
PS: when you ask about an error, post the complete and exact error message.
Your factory not return any thing (Read this). Its should be like this
securityApp.factory('getToken', function ($scope, $http) {
return {
getAccessToken: function () {
$http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: $scope.userName, password: $scope.password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).success(function (data, status, headers, config) {
return data.access_token;
});
},
};
});
and call it in your controller like below.
securityApp.controller('membersController', function ($scope, $http, getToken) {
$scope.token = getToken.getAccessToken();
$http({ method: 'GET', url: '/api/Members/?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.then(function (response) {
$scope.members = response.data;
});
});
Update:
To solve the error: "Error: [$injector:unpr] Unknown provider change the code
securityApp.controller('membersController', ['$scope', '$http','getToken', function ($scope, $http, getToken) {
$scope.token = getToken.getAccessToken();
$http({ method: 'GET', url: '/api/Members/?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token} })
.then(function (response) {
$scope.members = response.data;
});
} ]);
Demo Sample

Angular Factory returns token via $q promis

I am trying to create a factory that will return a token to the controller. This code only works as far as getting the token from the server but does not pass the token back into the controller. The token just comes back empty inside the controller. Please advise. Thank you.
securityApp.factory("getTokenFromServer", function ($http, $q) {
var token;
function getToken(userName, password) {
var deferred = $q.defer();
$http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).then(function (data) {
token = data.access_token;
deferred.resolve(token);
});
return deferred.promise;
}
return {
getToken: getToken
};
});
securityApp.controller('membersController', function ($scope, $http, getTokenFromServer) {
$scope.username = 'aharris1#test.com';
$scope.password = 'SuperPass1!';
getTokenFromServer.getToken($scope.username, $scope.password).then(function (data) {
$scope.token = data;
alert($scope.token);
$http({ method: 'GET', url: '/api/Members/?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.then(function (response) {
$scope.members = response.data;
});
});
});
That is because you are not accessing the data in the right way. When using then chain of the promise the result is a combination of data, status etc.. (when opposed to success call back which breaks up pieces and give you data right up as the first argument) So i believe you should look for result.data.access_token instead of result.access_token
.then(function (result) {
token = result.data.access_token;
deferred.resolve(token);
});
And with you have you can just simplify your api method to return http promise itself rather creating a defered object:-
securityApp.factory("getTokenFromServer", function ($http, $q) {
function getToken(userName, password) {
return $http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).then(function (result) {
return result.data.access_token; //Return the data
}, function(errorResponse) {
return $q.reject(errorResponse.data);//Reject or return
});
}
return {
getToken: getToken
};
});

Resources