2014-12-04 150 views
0

我在我的角應用中使用ui路由器。 我定義的路由這樣的:使用ui路由器跳過解決更改路由

angular.module('app.product', []) 

.config(['$stateProvider', function($stateProvider) { 
    $stateProvider 
    .state('product', { 
     url: '/product/:product_id', 
     templateUrl: 'partial/product', 
     controller: 'productCtrl', 
     resolve: { 
     product: ['$http', '$stateParams', 
      function($http, $stateParams) { 
      return $http.get('/api/product/' + $stateParams.product_id); 
      }] 
     } 
    }) 
}]) 

在某一點,我手動更改使用$state.go('product')客戶端的路由。這裏我已經在客戶端有product數據,所以不需要額外的$http請求。

什麼是在$state.go調用中傳遞數據的最佳方式,並讓ui-router知道不需要提出此請求?

我應該建立一個服務來處理這個問題嗎?

+0

所以你想要某種緩存?您應該爲此使用服務/工廠並檢查所有緩存相關信息。我認爲angular http已經支持緩存,請檢查一下。 – 2014-12-04 09:09:24

+0

把這段代碼放在一個服務中,而不是在你的控制器的解析中,那麼你可以保留一個本地副本pf中的數據,當它是空的時候發一個serer調用,否則返回它。 – 2014-12-04 09:20:52

回答

1

使用服務(類似下面的代碼)。請注意,這是我的頭頂。

.config(['$stateProvider', function($stateProvider) { 
    $stateProvider 
     .state('product', { 
      url: '/product/:product_id', 
      templateUrl: 'partial/product', 
      controller: 'productCtrl', 
      resolve: { 
       product: ['ProductCache', '$stateParams', 
       function(ProductCache, $stateParams) { 
        return ProductCache.getProduct($stateParams.product_id); 
       }] 
      } 
     }); 
}]) 
.factory('ProductCache', ['$http', '$q', function($http, $q) { 
    var cache = []; 
    return { 
     getProduct: function(id) { 
      // return the product if available, otherwise from the api 
      if(!cache[id]){ 
       return $http.get('/api/product/' + id, function(result){ 
        cache[id] = result.product; // or however your api return is structured 
        return cache[id]; 
       }); 
      }else{ 
       // use .when() to ensure a promise is returned to the resolve function 
       return $q.when(cache[id]); 
      } 
     } 
    }; 
}]);