使用 Angular 服务链接 http.get 承诺 [英] chaining http.get promises with angular service

查看:44
本文介绍了使用 Angular 服务链接 http.get 承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一种糟糕的方式吗?我基本上是在链接承诺,每次从服务器成功返回时,都会启动一个新的 http.get() 以获取更多信息,但不会在出错时启动.如果导致 errorCallback,则不再使用 http.get()s!

Is this a bad way to do this? I'm basically chaining promises, where each successful return from server, launches a new http.get() for more information BUT NOT when it errors. No more http.get()s if it causes an errorCallback!

$http.get(...).then(function() {
  $http.get(...).then(function(){ 
      $http.get(...).then(function(){}, function(){}), 
   function(){}); }, 
mainErrorCallback);

如果它不是$http.get()",它会在

Would it make a difference if it was instead of "$http.get()" it does "ViewsService.loadViews()" inside the

$http.get(...).then( function() { ViewsService.loadViews(); }, function(){ console.log("error"); }). 

这就是我的意思,同步.. 似乎它有效,但代码需要清理/效率才能看起来更整洁:

http://jsfiddle.net/4n9fao9q/6/

(带有延迟的 http 请求):http://jsfiddle.net/4n9fao9q/26

(with delayed http requests): http://jsfiddle.net/4n9fao9q/26

推荐答案

$http.get(...).then((res) => {
  //res has data from first http
  return $http.get(...);
}).then((res) => {
  //res has data from second http
  return $http.get(...);
}).then((res) => {
  //res has data from third http
}).catch((err) => {
  //exploded
});

我认为更干净.您可以将 $http.get 替换为任何返回承诺的函数.如果 ViewsService.loadViews() 返回一个 promise,您可以使用它.

I think is cleaner. You can replace $http.get with whatever function returns a promise. If ViewsService.loadViews() returns a promise, you can use it.

如评论中所问.

...
ViewsService.loadViews = function() {
  //returns a promise
  return $http.get(...);
}

OR

ViewsService.loadViews = function() {
  return new Promise((resolve, reject) => {
    $http.get(...).then((result) => {
      //whatever
      return resolve();
    })
  })
  return $http.get(...);
}

使用任何用于 loadViews 的选项,您都可以执行 ViewsService.loadViers.then(etc)

With any of this options for loadViews you can do ViewsService.loadViers.then(etc)

这篇关于使用 Angular 服务链接 http.get 承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆