1

I have a POST data to retrive in a Angular.js project. This is my factory:

angular.module('mtApp').factory('getKey', function($http) {
    return {
        getData: function(data) {
            var key='';
            return $http({
                url: '../php/key_gen.php',
                method: "POST",
                headers: {'Content-Type': 'application/json'}
                }).success(function (data) {
                    console.log(data); //value is right as expected
                    return data;
                })
                .error(function (data, status, headers, config) {
                    console.log('Erro : ' + status + ' ' + headers);
                });
        }
    }
});

The way I´m getting the data is:

$scope.key = 'ok';

getKey.getData()
.success(function($scope,data){
    $scope.key = data.GeneratedKey;
    console.log(data.GeneratedKey); //undefined
    console.log(data);  //200 o.O
});

console.log($scope.key); //still 'ok' O.o

As you can see in my code I have several console.log calls. When I run the application the only thing I see is:

mtapp.controller.js:13 ok
mtapp.app.js:52 Object {GeneratedKey: "d1bc7a5e840a6c24d87b90dde9e075de1f0e3b34978ca9f319…69d839b4e2a004e1f8d728939867afe189cfb8848c6a8ee38"}
mtapp.controller.js:9 undefined
mtapp.controller.js:10 200

The value in line mtapp.app.js:52 should be the same as mtapp.controller.js:10. But the object from the factory has only a value of 200 when I try to view in the log...

My objective is get the value from the JSON in the factory (GeneratedKey) to the controller (in the $scope.key).

What am I doing wrong? :(

8
  • why are you accepting the first argument of the success callback as $scope? Judging by the callback you used in your factory, you know that should be data instead... the second argument is the status code. Commented Apr 23, 2015 at 19:01
  • I should be .success(function(data,$scope){ ? Commented Apr 23, 2015 at 19:03
  • 2
    .success(function(data, statusCode){ Commented Apr 23, 2015 at 19:04
  • Not working yet. The line console.log($scope.key); //still 'ok' O.o still printing only 'ok'. Commented Apr 23, 2015 at 19:23
  • it's supposed to print 'ok'. ajax is asynchronous. Commented Apr 23, 2015 at 19:23

3 Answers 3

2

Because you are dealing with second parameter which is status code, you should remove $scope from there and use data itself

Code

getKey.getData()
.success(function(data, status, headers, config){ <---here $scope should remove
    $scope.key = data.GeneratedKey;
    console.log(data.GeneratedKey);
    console.log(data);
});
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome! That´s the problem. But I just don´t know why I have used this. Problably a wrong use of an example. :(
@dipievil What example? Have you tried to read documentation – docs.angularjs.org/api/ng/service/$http
@KrzysztofSafjanowski It was pretty straight forward
There´s still a problem. $scope.key = ''; getKey.getData() .success(function(data){ $scope.key = data.GeneratedKey; console.log(data.GeneratedKey); }); console.log($scope.key); $scope.key still empty. I think that´s why I put $scope in the call.
@dipievil you should not pass $scope to the service
0

As Kevin said the main problem is the asynchronous way that angular.js works.

Só the big problem is that the last line

console.log($scope.key); //still 'ok' O.o

need to be set before the end of the function that call the factory. And the $scope has been removed from the function to work properly as pankajparkar said.

$scope.key = 'ok';

getKey.getData()
.success(function(data){ // removed the $scope
    $scope.key = data.GeneratedKey;
    console.log($scope.key); //Moved up and it shows correctly in the console
    ... the rest of my code ...
});

I don´t know if it is the best solution, but works now! :D

2 Comments

You miss the part that Kevin said.
are you talking about asynchronous part? that was obvious while you are making ajax?
-1

Try using $q in your factory instead.

angular.module('mtApp').factory('getKey', function($http, $q) {
    var  getData= function(data) {
            var key='';
            var url = '../php/key_gen.php';
            var returned = $http.post(url, data);
            return $q.all(returned);

        };
     var getKey = {
    getData: getData

  };


  return getKey;
});


$scope.key = 'ok';

getKey.getData(someData).then(function (response, status, headers, config) {
    console.log(response.data.GeneratedKey);
});

5 Comments

Don´t know why the someData. I want to get the data FROM the factory, not to send to it. Removing it I got the error TypeError: Cannot read property 'GeneratedKey' of undefined
your getData accepts a parameter hence the someData. You should be able to get your GEneratedKey from response. What does response.data return in the console?
This is an anti-patern. There is no reason to unwrap a promise just to wrap it again. Just return the promise returned by $http.post(...)
someData is a variable?!
If you dont need a parameter in getData, you'll need to remove it in your factory. So yes, it is a variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.