我经常在网上看到有关 Angular 服务的教程和代码片段,这些服务进行 $http 调用,返回 $http promise 和一些数据。如果将 promise 返回给 Controller ,那么在服务中返回数据有什么意义呢?我什至不明白它被归还到哪里。这是我的意思的一个例子:
// Function of MyStuffService:
function getStuff() {
return $http.get('/api/stuff')
.success(function(data) {
// Why return data here? How could I even get this returned value?
return data;
})
.error(function(data) {
console.error(data);
});
}
// Controller:
function getStuff() {
MyStuffService.getStuff()
.success(function(data) {
$scope.stuff = data;
})
}
我不能将我的服务函数重写为:
// Function of MyStuffService:
function getStuff() {
return $http.get('/api/stuff')
.error(function(data) {
console.error(data);
});
}
然后让 Controller 从返回的 promise 中获取数据?我觉得我不明白这里的东西。非常感谢任何帮助。
最佳答案
.then
中返回的数据可供下一个链式 .then
处理程序使用,这是您最终用来获取数据的处理程序。
.success
只是传递了 $http.get
的原始 promise 。从 .success
返回数据不会执行任何操作。
所以,如果你有:
function getStuff() {
return $http.get('/api/stuff')
.success(function(data) {
// do something with data. returning doesn't do anything
})
.error(function(data) {
console.error(data);
});
};
在 Controller 中你会做:
getStuff().then(function(response){
$scope.data = response.data; // this is the data available from `$http.get`
}
关于javascript - 为什么在 Angular 服务中使用 $http 时返回 promise 和数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28748483/