2016-04-10 30 views
1

我需要我的服務從服務器返回帶有信息的json。無法在AngularJS服務中返回對象類型

服務代碼:

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;    
      }   
      }) 
    } 
}) 

下面是來自控制器代碼。

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

請求服務器成功,但功能返回未定義。 我也嘗試添加return語句之前取()的服務,而且我在日誌了:

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

爲獲取方法提供回調函數 –

回答

0

你的fetch()方法目前不返回任何東西。所以它實際上返回undefined

所以你要添加一個return語句。這將使該函數返回承諾。它不能返回數據,因爲提取是異步操作。所以它返回一個承諾。這意味着,調用者必須

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

相反,它必須做

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; 
    } 

現在你的控制器內,調用服務的方法的數據分配給範圍變量和迭代/必要時解析。

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格式明確設置標頭對象。如果您將來需要設置標題,您可以通過在$ http方法中以與您所做的幾乎相同的格式添加它來完成此操作。 有關$ http的更多信息,請參考ngdocs