0

I am creating a login controller on Angular and I have a factory service in which I send a post request and return json data. When I console.log the success data I can see an object however when i try to access the properties I am getting undefined.

UserAuthFactory.login(name,password)
        .success(function(data){
            console.log(data.token);
            AuthenticationFactory.token = data.token;
            console.log(data);
        }).error(function(status){
            console.log('oops something went wrong.');
        });
};

in my console.log

Object {success: true, message: "Enjoy Your Token!", token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1N…jowfQ.Hcfejg7x7W4w01fBaf303I2iJ57T38e84vLtGDiwSHI"} message: "Enjoy Your Token!"success: truetoken: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NjUzODEyNjg2NzFhM2JhMmQ2NTQ4NjgiLCJuYW1lIjoiTmljayBHbG9uYXJpcyIsInBhc3N3b3JkIjoicGFzc3dvcmQiLCJhZG1pbiI6dHJ1ZSwiX192IjowfQ.Hcfejg7x7W4w01fBaf303I2iJ57T38e84vLtGDiwSHI"proto: Object app.js:121 undefined

How can I then access the different properties of the array? Properties such as token, message, etc?

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
arsenalist
  • 391
  • 4
  • 18

2 Answers2

1

If you want to access that data in HTML part, refer to my example code.

I did use $scope, $http module.

example.controller('Example', function( $scope, $http ) {

    $scope.token = '';
    $scope.message = '';
    $scope.etc = null;

    $scope.getToken = function() {

        var reqParams = { id: 'userid', password: 'owije3wefo' };
        $http.post('getToken', reqParams ).then( function( res ) {

            console.log( res.data );
            this.result = res.data.token;
            this.message = res.data.message;
            this.etc = res.data.etc;

        }.bind(this));
    };
});

In html,

<div ng-controller="Example">
    <div>
        <span class="label">token</span>
        <input ng-model="token" type="text" />
    </div>
</div>
Alfred
  • 1,276
  • 11
  • 19
0

When you have a JSON object you should only convert it with the function JSON.parse(text)

For example

var json_object = JSON.parse(json_string);
console.log(json_object.parameter);
Giacomo Torricelli
  • 764
  • 1
  • 6
  • 21