2014-12-04 155 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]); 
      } 
     } 
    }; 
}]);