ashish kumar
ashish kumar

Reputation: 67

undefined object when using factory for authentication service in angularjs

I have created a factory service in angularjs, which has an authentication service in it. If the authentication succeeded then it generates a token which is required for the dashboard services. I am able to generate the token but not understand how to use it.

Is it a good idea to create a factory service to get a token so I should inject in controllers as needed?

login.html:

<div ng-app="loginFormApp" ng-controller="loginFormCtrl">
    <form method="post" action="" id="login_form" class="row">
        <input type="text" placeholder="Login ID" ng-model="loginId" >
        <input type="password" placeholder="Password" ng-model="password" >
        <input type="button" class="btn btn-theme" ng-click="loginCall()" value="Login">
        <input type="button" class="btn btn-theme" ng-click="loginCall()" value="Register Here">
    </form>
</div>

My controller and factory service (authService.js):

var app = angular.module('loginFormApp', []);
 app.controller('loginFormCtrl', function ($scope, AuthService) {
     $scope.loginCall = function () {
         var token= AuthService.authentication($scope.loginId, $scope.password);
         alert(token);

     };
 });

 app.factory('AuthService', function ($http) {
     return {
         authentication: function (UserName, Password) {
             $http.post("http://103.19.89.152:8080/ccp-services/authenticate", {
                     'userName': UserName,
                     'password': Password
                 })
                 .then(function (response) {
                         window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
                         var getToken = response.data.httpHeaders.h5cAuthToken;
                      //   alert(token);
                 
                     },
                     // Error Handling
                     function (response) {
                         console.log(response.datas);
                     });
         }
         
     }
 });

Upvotes: 0

Views: 1116

Answers (3)

Vadiem Janssens
Vadiem Janssens

Reputation: 4109

This code does not work, because $http.post returns a promise.

var token = AuthService.authentication($scope.loginId, $scope.password);

First of all, you should return the $http.post method, as shown below.

return $http.post( // rest of code

In the then method after the $http.post, you should return the token.

.then(function (response) {
    window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
    return response.data.httpHeaders.h5cAuthToken; //return token
},

And the login call in your controller should be

AuthService.authentication($scope.loginId, $scope.password).then(function(token) {
    alert(token);
});

Update 1: reusing the access token

Ofcourse you want to be able to reuse the access token in API calls after the authentication call. This can be done by doing the following. Instead of returning the access token to the calling method, you can 'cache' the token inside the service itself.

app.factory('AuthService', function ($http) {
    var cachedToken; // this is where the token will be saved after authentication
    return {
        authentication: function (UserName, Password) {
            $http.post("http://103.19.89.152:8080/ccp-services/authenticate", {
                'userName': UserName,
                'password': Password
            })
            .then(function (response) {
                window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
                cachedToken = response.data.httpHeaders.h5cAuthToken; // save token to 'cache'
                return cachedToken
            },
            function (response) { // Error Handling
                console.log(response.datas);
            });
        },
        getToken: function() { // new method to retrieve the cached token
            return cachedToken;
        }
    }
});

In your dashboard controller, you can retrieve the token with:

AuthService.getToken();

Ofcourse, you need additional code to check if a token is actually retrieved (otherwise you will get undefined).

Upvotes: 2

Anandhan Suruli
Anandhan Suruli

Reputation: 365

Use the below factory. I added a return in $http call.

app.factory('AuthService', function ($http) {
 return {
     authentication: function (UserName, Password) {
       return  $http.post("http://103.19.89.152:8080/ccp-services/authenticate", {
                 'userName': UserName,
                 'password': Password
             })
             .then(function (response) {
                     window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
                     var getToken = response.data.httpHeaders.h5cAuthToken;
                  //   alert(token);

                 },
                 // Error Handling
                 function (response) {
                     console.log(response.datas);
                 });
     }

 }

});

Upvotes: 0

Constantine
Constantine

Reputation: 512

$http.post invokes asynchronously, so you have to use callback to get token variable, authentication function will not return it.

Upvotes: 0

Related Questions