Can';t在AngularJS服务中返回对象类型
我需要我的服务从服务器返回带有信息的json 服务守则:Can';t在AngularJS服务中返回对象类型,angularjs,service,Angularjs,Service,我需要我的服务从服务器返回带有信息的json 服务守则: app.service('Server', function () { this.fetch = function (data, token) { fetch('http://104.197.58.108:8080', { method: 'post', headers: { 'Accept': 'application/json',
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);
请求服务器成功,但函数返回未定义。
我还尝试在服务中的fetch()之前添加return语句,这就是我在日志中得到的:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
您的fetch()方法当前不返回任何内容。因此它实际上返回未定义的
因此,您需要添加一个return语句。这将使函数返回成为一种承诺。它不能返回数据,因为提取是一个异步操作。因此,它回报了一个承诺。这意味着调用方必须不执行
$scope.materialist = Server.fetch($scope.data2, $rootScope.token);
它必须这样做
Server.fetch($scope.data2, $rootScope.token).then(function(data) {
$scope.materialist = data;
});
您的fetch()方法当前不返回任何内容。因此它实际上返回未定义的
因此,您需要添加一个return语句。这将使函数返回成为一种承诺。它不能返回数据,因为提取是一个异步操作。因此,它回报了一个承诺。这意味着调用方必须不执行
$scope.materialist = Server.fetch($scope.data2, $rootScope.token);
它必须这样做
Server.fetch($scope.data2, $rootScope.token).then(function(data) {
$scope.materialist = data;
});
现在在控制器内部,调用服务的方法,将数据分配给scope变量,并根据需要进行迭代/解析
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格式显式设置headers对象。如果将来确实需要设置头,您可以通过在$http方法中添加头来实现,格式与您所做的几乎相同。
有关$http的更多信息,请参阅
现在在控制器内部,调用服务的方法,将数据分配给scope变量,并根据需要进行迭代/解析
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格式显式设置headers对象。如果将来确实需要设置头,您可以通过在$http方法中添加头来实现,格式与您所做的几乎相同。
有关$http的更多信息,请参阅为fetch方法提供回调函数为fetch方法提供回调函数