2017-02-16 36 views
0

我的角度應用程序分爲4個模塊,所有模塊都需要用戶的細節,所以我從每個模塊的調用方法的getUser。因此,當我的應用程序加載所有4個模塊時,同時觸發getUser API,從而在服務器上產生4個獲取請求。我怎樣才能防止這一點?我在我的getUser方法中使用單例模式,所以一旦我的用戶被加載,它將僅僅從一個對象服務用戶。但是,如果所有模塊同時向用戶請求,這並不能解決問題。同時處理GET調用angularjs

我的代碼看起來像這樣

getUser() { 
let defer = this.q.defer(); 

if (!this.user) { 
    this.http.get(`${this.config.apiHost}users`) 
     .success(result => { 
      this.user = result; 

      this.rootScope.$broadcast('userFound', this.user); 
      defer.resolve(this.user); 
     }) 
     .error(err => defer.reject(err)) 
} 
else { 
    defer.resolve(this.user); 
    this.rootScope.$broadcast('userFound', this.user); 
} 
return defer.promise; 
} 
+0

添加呼叫的服務裏面。該服務將檢查用戶對象是否存在。如果是這種情況,它會返回對象 - 如果沒有,則返回get調用。 **或**您可以緩存呼叫 – Weedoze

+0

我已經擁有僅在服務中定義的方法,它會檢查用戶對象是否存在。但是,當所有模塊試圖同時獲得用戶時,這種方法不起作用。 –

+0

你使用ui-router嗎? ..我可以建議你在路由使用解決方法,並請求傳遞給你的控制器的結果.. –

回答

1

通過存儲當前請求的變量調用UserService.get將返回相同的請求承諾。

那麼當承諾解決,這將解決您的所有模塊。

angular.module('app').service('UserService', function ($http) { 

    var self = this; 

    var getRequestCache; 

    /** 
    * Will get the current logged in user 
    * @return user 
    */ 
    this.get = function() { 
     if (getRequestCache) { 
      return getRequestCache; 
     } 

     getRequestCache = $http({ 
      url: '/api/user', 
      method: 'GET', 
      cache: false 
     }).then(function (response) { 
      // clear request cache when request is done so that a new request can be called next time 
      getRequestCache = undefined; 
      return response.data; 
     }); 

     return getRequestCache; 
    }; 

}); 
0

您正在使用ui-router進行路由。然後,您可以使用它在登陸頁面時解析用戶。

在你的路由配置:

$stateProvider 
    .state('myPage', { 
     url: '/myPage', 
     templateUrl: 'myPage.html', 
     controller: 'myCtrl', 
     resolve: { 
      userDetails: ['UserService', function(UserService) { 
       return UserService.getUserDetails(); 
      }], 
     } 
    }) 

在你的控制器

angular.module('myModule') 
    .controller('myCtrl', ['userDetails', function(userDetails) { 
     console.log(userDetails); 
     }]; 

這將在加載頁面加載用戶的詳細信息。

0

我用推遲對象,使之僅僅被初始化一次全局對象解決了這個問題。