在角使用承诺,服务于一体 [英] Use Promise and service together in Angular

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

问题描述

我的问题是基于在谷歌角组这个话题。结果
我想提供一种存储从通过$ HTTP后台检索的一些基本数据的服务,那么我只需要一次读取这些数据。喜欢,

My question is based on this topic in Angular Google group.
I want to provide a service which stores some basic data retrieved from the backend via $http, then I only need to fetch those data once. like,

var load = function() {
   return $http.get(...).then(function(data) {
       return data.user; 
   });
};

module.factory("userProvider", function() {
    var user;
    var getUser = function() {
        if(!user) {
            load().then(function(data) {
               user = data;
           });
        }
        return user;
    };
    return {
        getUser : getUser
    }
});

module.controller("UserController", ["userProvider", function UserController("userProvider") {
    var user = userProvider.getUser();
    // do something with user
}]);

问题是,许链userProvider结束,但没有控制器,因此用户是不明确的,我第一次使用这个控制器,因为数据没有得到回报。

The problem is that the promise chain ends in userProvider but not in controller, so the user is undefined the first time I use this controller since the data has not been returned.

如何使用这种存储服务,并返回正确的数据?谢谢!

How can I use such a storage service and return the data correctly? Thanks!

推荐答案

您可以直接创建自己的诺言。下面是修改code:

You can just create your own promise. Here is the modified code:

module.factory( "userProvider", function( $q ) {
  // A place to hold the user so we only need fetch it once.
  var user;

  function getUser() {
    // If we've already cached it, return that one.
    // But return a promise version so it's consistent across invocations
    if ( angular.isDefined( user ) ) return $q.when( user );

    // Otherwise, let's get it the first time and save it for later.
    return whateverFunctionGetsTheUserTheFirstTime()
    .then( function( data ) {
      user = data;
      return user;
    });
  };

  // The public API
  return {
    getUser: getUser()
  };
});


更新:按@yohairosen下面的解决方案是许多情况下,一个伟大的,但不是所有的。在某些情况下,我们只想要缓存的成功的结果,因为我在这里做。如果,例如,该请求的失败表示用户需要先登录,我们不希望在下次调用(登录后presumably),可提供缓存失败。在情况下,该方法不是从电话到电话在任何情况下一定是一致的,这种方法比较好;在其他情况下,@ yohairosen的解决方案是简单和建议。


Update: The solution below by @yohairosen is a great one for many circumstances, but not for all. In some circumstances, we would only want to cache the successful result, as I have done here. If, for example, a failure of this request indicates the user needs to log in first, we would not want the next call (presumably after logging in) to deliver the cached failure. In cases where the method isn't necessarily consistent from call-to-call in all circumstances, this method is better; in all other cases, @yohairosen's solution is simpler and recommended.

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

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