I recently had a requirement to create a custom component that would make a
REST call to an API and then return data (a token) back. I'm working with
Angularjs 1.4.2.
So I created a custom directive that called a service to do this, however,
I kept failing to return the data back to the directive. All I would get
was a promise back, except within the context of the $http.post code in the
service and I was unable to get the value of the data from the promise.
The solution was to have two return calls from $http.post. My question is,
where is this documented? Maybe I'm just missing something here, but I
spent a lot of time on this for a solution and this was the only one I
could get to work. I never could find this in the Angular docs, but I have
missed some things before. The solution came due to help from another dev
who couldn't remember how they found this pattern.
Here is some of the code snippets:
//custom directive
$scope.login = function () {
var loginResponse = {};
var errorMessage = "";
var access_token = "";
loginService.login(myInfo).then(function(response) {
console.log("response is: " + JSON.stringify(response));
if(response.data.token) {
$window.sessionStorage.setItem("token", response.data.token);
}else{
errorMessage = response.data.errorMessage.split(":").pop();
console.log("errorMessage is: " + errorMessage);
... more code
//service
function loginService($window, $http, $httpParamSerializerJQLike) {
var service = {
login:login
};
return service;
function login(myInfo) {
... more code here
params = $httpParamSerializerJQLike(params);
console.log("The params are: " + params);
return $http({
url: baseURL,
method: 'POST',
data: params,
//Set the headers so Angular is passing information as form data, not
request payload.
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function onSuccess(response) {
return response;
}).catch(function onError(response) {
return response;
});
}
My questions are is this is a good pattern to use for this scenario and if
not, what is better? Again, I'd like to know who came up with the pattern
and where it's documented?.
Thank you,
James
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.