2016-04-10 24 views
1

Sunucumdan bilgi içeren bir json döndürmek için hizmetime ihtiyacım var. hizmetinAngularJS hizmetinde bir nesne türü döndürülemiyor

Kodu:

app.service('Server', function() { 

    this.fetch = function (data, token) { 
    fetch('http://104.197.58.108:8080', { 
      method: 'post', 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json' 
      }, 
      body: JSON.stringify({ 
       data: data, 
       token: token 
      }) 
     }) 
      .then(function(response) { 
      return response.json() 
      }).then(function(text) { 
      if (text.success == false) { 
       return false; 
      } else { 
       return text;    
      }   
      }) 
    } 
}) 

İşte denetleyicisinden kod.

$scope.data2 = '{"func":"materialSons","material":"0"}'; 
    console.log(Server.fetch($scope.data2, $rootScope.token)); 
    $scope.materialist = Server.fetch($scope.data2, $rootScope.token); 

Sunucu başarılarını isteme, ancak işlev tanımsız olarak döndürür.

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} 
+0

Geri getirme yöntemine bir geriçağırım işlevi sağlama –

cevap

0

Kişisel getirme() yöntemi şu anda hiçbir şey dönmez: Ben günlüğüne ne var hizmetinde Ben de eklemeden return ifadesi önce getirme çalıştı() ve bu,. Yani aslında undefined döndürür.

Böylece bir return ifadesi eklemelisiniz. Ve bu işlev işlevinin bir sözünü döndürmesini sağlayacaktır. Getiri eşzamansız bir işlem olduğundan veri geri dönemez. Yani bir söz verir. Yani arayan değil,

$scope.materialist = Server.fetch($scope.data2, $rootScope.token); 

yerine controller içerisinde Şimdi

Server.fetch($scope.data2, $rootScope.token).then(function(data) { 
    $scope.materialist = data; 
}); 
0
app.service('Server', function ($http) { 

    this.getData = function(){ 
    var promise = $http({ 
    method : 'GET', 
    url: 'http://104.197.58.108:8080' 
    }).then(function(data){ 
     return data; 
    }, function(error){ 
     return error; 
    }); 
    return promise; 
    } 

yapmalısınız yapmak hizmetin yöntemini çağırın bir kapsam değişken ve yineleme veri atamak gerektiği anlamına gelir/gerektiği şekilde ayrıştırın.

Server.getData().then(function(response){ 

$scope.fetchedData = response; 

//Open the Sources tab by pressing in dev tools and see the format of the response by setting debugger points. 
// or $scope.fetchedData and parse and assign the values accordingly. 

}); 

JSON biçiminde üstbilgi nesnelerini açıkça ayarlamanız gerekmeyecek gibi hissediyorum. Gelecekte üstbilgileri ayarlamanız gerektiğinde, bunu yaptığınız gibi hemen hemen aynı biçimde $ http yöntemine ekleyerek bunu yapabilirsiniz. $ http ile ilgili daha fazla bilgi için, bkz. ngdocs

İlgili konular