javascript - 为什么在 Angular 服务中使用 $http 时返回 promise 和数据?

标签 javascript angularjs angular-promise angularjs-http

我经常在网上看到有关 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/

相关文章:

javascript - 调用 JSON.stringify 时检测父对象

javascript - 如何正确使用显示: inline with ng repeat

javascript - 页面重新加载后显示警报消息

javascript - 向 $q.all() 添加 promise

javascript - AngularJS 在 Promise 中嵌套 Promise.all 只返回第一个

javascript - 如何像在 Python 中那样在 Google Apps 脚本中对字符串进行切片?

javascript - 直接从 GitHub 热链接资源,例如 JavaScript 文件

java - 一个单元如何测试非确定性加密函数?

javascript - Angular 1.5 组件没有将变量传递给组件

javascript - .then 的 AngularJS 条件案例基于仅在第一个 .then 之前已知的 var 值