0
ng.module('app')
    .service('CardService', ['$http', CardService])

function CardService($http) {
    this.$http = $http;
    var self = this;

  $http.get('http://localhost:3000/db').success(function(data) {
      self.items = data;
      console.log(self.items);
  });
  console.log(self.items);
}

CardService.prototype.list = function() {
        console.log(self.items);
        return this.items;
};

and result

service.js:14 undefined

service.js:18 undefined

service.js:18 undefined

service.js:12 [Object, Object, Object]

How do I solve this problem?

Community
  • 1
  • 1
Limarenko Denis
  • 769
  • 1
  • 8
  • 13
  • 4
    Stop thinking synchronous. That Ajax request takes time to complete and your code will not hang and wait. Also use .then not .success. Its deprecated. – ste2425 Jun 03 '16 at 08:09
  • [Don't make asynchronous requests inside constructors](http://stackoverflow.com/q/24398699/1048572). – Bergi Jun 03 '16 at 08:14
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/q/23667086/1048572) – Bergi Jun 03 '16 at 08:15
  • You should at least mark some answer correct or vote them up.. answering question needs some research... and the ones who answers deserve vote up.. – Tirthraj Barot Jun 15 '16 at 17:03

2 Answers2

0

The ajax call is async. It will allow the thread to move on while it waits for a response from the .get

the console.logs you are doing will then be called in this order.

  1. console.log right below your ajax call
  2. console.log inside list prototype

(inside ajax success)

  1. console.log inside list prototype
  2. console.log below self.items = data

Not the angular way, but... the prototype should used only when the list is initialized inside the ajax call.

Stian Standahl
  • 2,506
  • 4
  • 33
  • 43
0

According to best practices, you should do all the http request related stuff to get data using factory or service. As it is asynchronous flow, $q shall be used to handle it. So your functionality would be done as given below. Kindly correct me if i have misinterpreted your question.

app.factory('CardService',function($http,$q) {
var obj = {};

    obj.getCardServiceData = function(){
        var defer = $q.defer();
        $http.get('http://localhost:3000/db').then(function(response) {
         defer.resolve(response.data);
       },function(error){
          defer.reject(error);
       });
       return defer.promise;
    }

    return obj;

});

app.controller('YOUR CONTROLLER',function($scope,CardService){
      CardService.getCardServiceData().then(function(response){
           $scope.self = response.data;
           console.log($scope.self);
       },function(error){
           alert("There seems to be some error!");
           console.error(error);

       });
});
Tirthraj Barot
  • 2,671
  • 2
  • 17
  • 33