my http request is not working after my token is expired in first refresh but in second refresh is work fine, but the function is executing fine what have done wrong. i work in angular frame
$http({
url: "http://localhost/ArisSystem/api/system/subsystem",
method: "GET",
dataType: 'json',
ContentType: 'application/x-www-form-urlencoded',
params: {
parentId: $scope.systemIdToLoad
},
headers: authHeaders
}).then(function (response) {
$scope.subsystem = response.data;
}), function (xhr, status, error) {
if (refreshtoken && xhr.status === 401) {
$scope.refreshlocal();
}
}
$scope.refreshlocal = function () {
$.ajax({
url: "http://localhost/ArisSystem/login",
data: {
refresh_token: refreshtoken,
grant_type: 'refresh_token'
},
type: 'POST',
dataType: 'json',
ContentType: 'application/x-www-form-urlencoded',
success: AjaxSucceeded,
error: AjaxFailed
})
function AjaxSucceeded(response) {
localStorage.setItem('accessToken', response.access_token);
localStorage.setItem('refreshToken', response.refresh_token);
refreshtoken = localStorage.getItem('refreshToken');
accesstoken = localStorage.getItem('accessToken');
authHeaders.Authorization = 'Bearer ' + accesstoken;
}
function AjaxFailed(err, response) {
window.location.href = "login.html"
}
}
You have a typo in your then function. The error-callback is outside the argument list. Instead it should be this:
$http({
...
}).then(function (response) {
$scope.subsystem = response.data;
}, function (xhr, status, error) {
if (refreshtoken && xhr.status === 401) {
$scope.refreshlocal();
}
});
I simply moved the ) from the 5th line back after the error-callback function.
That ought to do it. I'd suggest you do change the second request from $.ajax to use the $http service as well, just to keep your code consistent.
Related
I can't access the output variable from my 1st http get request, i need this data for another http Post request.
None.
$scope.submit = function(x) {
$http({
method: "GET",
url: url + 'getOSchild',
params: { ncard: x }
}).then(function success(response) {
$scope.osChild = response.data;
console.log($scope.osChild) // this has an output
}, function error(response, status) {
console.log(response)
console.log(status)
});
$http({
method: "POST",
url: url + 'printOS',
data: JSON.stringify({
CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: $scope.osChild //this is null
}),
header: {
'Content-Type': 'application/json'
},
}).then(function success(response) {
console.log(response)
}, function error(response, status) {});
}
I need the $scope.osChild to be present in my http post request.
Simply chain the two XHRs:
function getOSChild (x) {
return $http({
method: "GET",
url: url+'getOSchild',
params: {ncard: x}
}).then(function success(response) {
$scope.osChild = response.data;
console.log($scope.osChild); // this has an output
return response.data;
},function error(response) {
console.log(response)
console.log(response.status);
throw response;
});
}
$scope.submit = function(x) {
getOSChild(x).then(function(osChild) {
$http({
method: "POST",
url: url+'printOS',
data:{ CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: osChild //chained
}
}).then(function success(response) {
console.log(response)
});
});
};
The .then method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining.
For more information, see
AngularJS $q Service API Reference - chaining promises
You're Missing the Point of Promises
first GET call is asynchronous so $scope.osChild setting null initially. so suggestion is to use Promises https://ng2.codecraft.tv/es6-typescript/promises/
$scope.getOSChild = function() {
var deferred = $q.defer();
$http.get(url + 'getOSchild')
.then(function onSuccess(response) {
$scope.osChild = response.data;
deferred.resolve(response.data);
}).catch(function onError(response) {
console.log(response.data);
console.log(response.status);
deferred.reject(response.status);
});
return deferred.promise;
};
$scope.submit = function(x) {
$scope.getOSChild().then(function (osChild) {
$http({
method: "POST",
url: url + 'printOS',
data: JSON.stringify({
CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: osChild
}),
header: {
'Content-Type': 'application/json'
},
}).then(function onSuccess(response) {
console.log(response);
}, function onError(response, status) {});
});
};
When I call addCategory, it suppose to add my new category and then call _initAdminController() to go back to my main page and refresh the data there. But what is happening is getcourselist and getsubjectlist in initAdminController are somehow running first and then addCategory runs last. Do you know what can cause this? Am I using then correctly?
function _initAdminController() {
$scope.pageIndex = "adminTab";
console.log("reloading data");
$http({
method : 'GET',
url : 'http://testserver.com:8082/getSubjectListService'
}).then(function successCallback(response) {
$scope.updatedSubjects = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
$http({
method : 'GET',
url : 'http://testserver.hughes.com:8082/getCategoryListService'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
$scope.addCategory= function(){
var name = $scope.addCategoryData.name;
var desc = $scope.addCategoryData.description;
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : { 'Content-Type': 'application/json' },
data : {
name: name,
description: desc
}
}).then(_initAdminController(), function errorCallback(response) {
console.log(response.statusText);
});
}
Also when I use then for http get, that case is working correctly. The http get finishes first and then my scope variable get updated.
And lastly before I tried the following code and in that case, successCallback doesn't run at all. So does this mean then only works for GET?
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : {
'Content-Type': 'application/json'
},
data : {
name: name,
description: desc
}
}).then(
function successCallback(response) {
_initAdminController()
},
function errorCallback(response) {
console.log(response.statusText);
}
);
The code:
}).then(_initAdminController(), ...);
Should be:
}).then(_initAdminController, ...);
I am trying to use Angular to authenticate against an authorization endpoint that I know works using Postman.
<script type="text/javascript">
var tokenGeneratorApp = angular.module('myApp', []);
myApp.controller('AuthenticationController', function ($scope, $http) {
var ac = this;
ac.authorizationToken = null;
ac.getAuthorizationToken = function () {
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
},
headers: {
'Content-Type': 'application/json'
}
}).then(_authenticationSuccess, _authenticationError);
};
// Private methods to handle promise results
function _authenticationSuccess(response) {
ac.authorizationToken = response.data;
ac.resultsDisplay = ac.authorizationToken;
};
function _authenticationError(response) {
ac.resultsDisplay = 'An error occured: ' + response.data;
};
});
</script>
When I call getAuthorizationToken()I get an Http 400 back. When I look into the response.data object there is an error saying error:"unsupported_grant_type". This is confusing to me because in the Postman client I specify that the grant_type as password and all works as expected.
I must be doing something wrong in the Angular code.
Had a very similar problem recently. Try removing the 'headers' and insert 'dataType' instead, as follows:
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
dataType: "json",
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
}
EDIT
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
"username=" + theUserName + "&password=" +
thePassword + "&grant_type=thePassword"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
//resolving => error:"unsupported_grant_type"
vm.BtnLogin = function () {
$scope.txtUsernamee;
$scope.txtPasswordd;
var client_credentials = $scope.txtUsernamee + $scope.txtPasswordd;
var auth = 'username=' + $scope.txtUsernamee + '&' + 'password=' + $scope.txtPasswordd + '&grant_type=password';
$http({
method: "POST",
url: '/token',
contentType: 'application/json',
data: auth
}).then(function success(response) {
//$('#successModal').modal('show');
console.log("ok")
},
function error(e) {
console.log(e)
}
);
};
This is my code:
$scope.doLogin = function() {
$http({
method: "POST",
url: "http://localhost:8000/api/v1/user/user_signin",
data: { username: $scope.user.username, password: $scope.user.password },
headers: { 'Content-Type': 'application/json' },
responseType:'json'
}).success(function (data) {
console.log('data success');
console.log(JSON.stringify(data));
})
.error(function(data, status, headers,config){
console.log('data error');
});
};
Consol says:
data success
null
What I do wrong?
P.S.: API request is correct - I checked it in postman.
You set responseType to 'json' make sure that your server side is also sending the response compatible to your format 'json'.
Or simply remove the response type check if it works
I have made a HTTP post API call to a URL.
I am getting the response, but I am confused how to write a success function, as there are many ways for it.
Here's my API call. Please help me how would the success function would be like?
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action':'view'
}
}
$http(req);
Angular uses promise internally in $http implementation i.e. $q:
A service that helps you run functions asynchronously, and use their
return values (or exceptions) when they are done processing.
So, there are two options:
1st option
You can use the .success and .error callbacks:
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action': 'view'
}
}
$http(req).success(function() {
// do on response success
}).error(function() {
});
But this .success & .error are deprecated.
Official deprecation notice
http://www.codelord.net/2015/05/25/dont-use-$https-success/
So, go for the 2nd option.
2nd Option
Use .then function instead
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action': 'view'
}
}
$http(req).then(function() {
// do on response success
}, function() {
// do on response failure
});
You need to write a success callback to retrive the data returned by your API.
$http(req)
.then(function (response) {
var data = resposne.data;
...
}, function (error) {
var errorStatusCode = error.StatusCode;
var errorStatus = error.Status;
...
});
Basically $http returns a promise and you need to write a callback function.
Or you can do something like this:
$http(req).success(function(respData) { var data = respData; ... });
$http(req).error(function(err) { ... });
This is success and error syntax
$http.get("/api/my/name")
.success(function(name) {
console.log("Your name is: " + name);
})
.error(function(response, status) {
console.log("The request failed with response " + response + " and status code " + status);
};
Using then
$http.get("/api/my/name")
.then(function(response) {
console.log("Your name is: " + response.data);
}, function(result) {
console.log("The request failed: " + result);
};
$http returns a promise that has a then function that you can use.
$http(req).then(function (data) { ...; });
The definition of then:
then(successCallback, failCallback)