里面我自己的角度服务,你怎么弄的返回值回调用该服务的控制? [英] Inside my own Angular service, how do you get the return value back to the Controller that called the service?

查看:73
本文介绍了里面我自己的角度服务,你怎么弄的返回值回调用该服务的控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找出在里面角HTTP $的成功和错误回调和承诺的然后的一部分。在$ HTTP服务返回的承诺。是成功回调的然后的例子吗?
如果我坚持$ HTTP我自己的服务中?我会怎么做呢?

I'm having trouble figuring out the success and error callbacks inside $http in angular and the "then" part of a promise. The $http service returns a promise. Is the "success" callback an example of a "then"? What if I stick $http inside my own service? How would I do this?

我觉得code是更容易显示我的问题:

I think code is easier to show my questions:

app.controller('MainCtrl', function ($scope, $log, BooksService) {
    BooksService.retrieveAllBooks().then(function(results) {
      $scope.allBooks = results;
    });
  });


app.factory('BooksService', function($http,$log) {
  var service = {
    retrieveAllBooks: function() {
      return $http({
        method: 'GET','https://hugebookstore.org/allbooks'
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
      }).success(function(data, status, headers, config) {
         var allbooks = transformDataIntoBooksArray(data);//this function exists and just takes raw data and turns them into Book objects
         return allbooks;/*how is this "success" callback related to the "then"() callback in app.controller above?*/
      };
      }).error(function(data, status, headers, config) {
        $log.error('here is an error'+data + status + headers + config);
      });
    }
  };
  return service;
});

有关 app.controller code问题:

Questions about the app.controller code:

我需要使用里面的 app.controller?

我只希望我的控制器使用 BooksService 来接我的所有图书的清单。在 BooksService 已经有一个然后式的条款,这是成功回调。好像我有一个unnecssary然后。真的吗?

I just want my controller to fetch me a list of all the books using the BooksService. The BooksService already has a "then" type of clause, which is the "success" callback. It seems like I have an unnecssary "then". Is that true?

另外,如果是然后之称,我可以把任何东西在则是的回调函数的参数?

Also, when is the "then" called, and can I put anything in the then's callback function's parameters?

我不明白,在默认情况下都提供什么参数,什么我可以补充。

I don't understand what parameters are supplied by default and what I can add.

有关 app.factory code问题:

Questions about the app.factory code:

首先,这就是我所理解的code做的事情。

First, this is what I understand the code to be doing.

我使用的工厂()方法,而不是服务提供角()方法创建一个 BooksService
我定义一个函数叫做 retrieveAllBooks()的引擎盖下,正在使用$ HTTP在角异步GET请求,这本身就是一种服务。 RetrieveAllBooks()是一个什么比周围的$ HTTP GET服务,这很容易让客户只需拨打 BooksService.retrieveAllBooks的一个封装() 并交由图书对象的数组。

I'm creating a BooksService using the factory() methods and not the service() methods available in Angular. I'm defining a function called retrieveAllBooks() that under the hood, is making an asynchronous GET request using $http in Angular, which itself is a service. RetrieveAllBooks() is a nothing more than a wrapper around the $http GET service, which makes it easy for clients to simply call BooksService.retrieveAllBooks() and be handed an array of Book objects.

当是成功回调执行,什么是它关系到在然后中的回调我 app.controller?

When is the "success" callback executed and what is its relation to the "then" callback in my app.controller?

它不会出现在我的成功里面,一个收益()回调是不断返回到 app.controller 。为什么?

It doesn't appear that a return value inside my success() callback is ever returned back to app.controller. Why?

我怎样才能获得allbooks阵列返回到app.controller这就是最初叫 BooksService.retrieveAllBooks()

How can I get the allbooks array returned back to the app.controller which is what originally called BooksService.retrieveAllBooks()?

是否有允许在成功回调其他参数?

Are there any other parameters allowed in the success callback?

我需要什么,从 retrieveAllBooks ()函数的定义返回?难道我返回 $ HTTP承诺独自一人,或者我需要收益从成功和双方东西错误回调呢?

What do I need to return from the retrieveAllBooks() function definition? Do I return the $http promise alone, or do I need to return something from both the success and error callbacks as well?

我知道这是冗长的,但我希望有人能帮助我,B / C这模式 - 分离出我的网络调用到自己的服务层相调用$ HTTP 我直接控制器层内,会一遍又一遍做。

I know this is longwinded but I hope that someone can help me, b/c this to pattern--separating out my network calls into its own service layer as opposed to calling $http directly inside my controller layer, will be done over and over again.

谢谢!

推荐答案

成功错误处理具体通过 $ HTTP 返回的承诺。然而,他们类似于。然后(功能onFulfill(){},功能onReject(){})

The success and error handlers are specific to the promise returned by $http. However, they're similar to .then(function onFulfill(){}, function onReject(){}).

这是给你,如果你想直接返回承诺或实现别的东西。

It's up to you if you want to return that promise directly or implement something else.

一般情况下,你的控制器不应该关心你的服务如何处理该请求。因此,在我看来,你不应该直接返回承诺。刚刚处理您的服务成功和错误情况。返回的结果,如果请求成功,如果请求失败抛出一个错误。

Generally, your controller shouldn't be concerned about how your service handled the request. Thus, in my opinion, you shouldn't return that promise directly. Just handle the success and error case in your service. Return the result if the request succeeds and throw an Error if the request fails.

然后,您可以使用通用的。然后(功能onFulfill(){},功能onReject(){})模式在你的控制器,因为这始终是有效的,并预计在角承诺。

You can then use the generic .then(function onFulfill(){}, function onReject(){}) pattern in your controller, as this is always valid and expected with promises in Angular.

onFulfill 回调总是收到你的结果作为一个参数,在 onReject 回调接收错误作为参数。

The onFulfill callback always receives your result as a parameter, the onReject callback receives the Error as a parameter.

所以,你有什么选择?要么放弃你的 .success .error 在服务回调​​干脆处理成功的情况下转型控制器,或创建一个新的延期承诺返回转换结果:

So, what options do you have? Either drop your .success and .error callbacks in your service altogether and handle the transformation in the success case in your controller, or create a new deferred promise to return the transformed results:

app.factory('BooksService', function($http,$log,$q) {
  var service = {
    retrieveAllBooks: function() {
      var deferred = $q.defer();
      $http({
        method: 'GET','https://hugebookstore.org/allbooks'
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
      }).success(function(data, status, headers, config) {
         var allbooks = transformDataIntoBooksArray(data);//this function exists and just takes raw data and turns them into Book objects
         deferred.resolve( allbooks );
      };
      }).error(function(data, status, headers, config) {
        $log.error('here is an error'+data + status + headers + config);
        deferred.reject( new Error( 'here is an error'+data + status + headers + config );
      });
      return deferred.promise;
    }
  };
  return service;
});

虽然,我们可以节省,如果我们考虑:
  - 错误是由角已经跟踪
  - 该延迟是过量,并且能够避免
  - 内容类型,并接受由角和塞雷尔语产生的反正。
  - 我们可以节省匿名包装为我们的行动

Although, we can save that if we consider: - Errors are tracked by Angular already - The deferred is excess, and can be avoided - Content-Type and Accept are generated by Angular and the serer anyway. - We can save the anonymous wrapper for our action

所以,我们最终有:

app.factory('BooksService', function($http) {
  return {
    retrieveAllBooks: function() { 
      return $http.get('https://hugebookstore.org/allbooks').
             then(transformDataIntoBooksArray); // Error tracked by Angular already
      }
    }
});

这篇关于里面我自己的角度服务,你怎么弄的返回值回调用该服务的控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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