Use Promise and service together in Angular

后端 未结 2 725
醉话见心
醉话见心 2021-02-05 07:10

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 t

2条回答
  •  难免孤独
    2021-02-05 07:40

    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()
      };
    });
    

    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.

提交回复
热议问题