How to use decorator to replace $resource object AngularJS -
How to use decorator to replace $resource object AngularJS -
i'm using decorator $resource service create base of operations url alter whenever route of application changes.
the route setup in way:
.state('root', { url: '/{shop_id:[0-9]{0,4}}', abstract: true, params: { shop_id: {squash: true} }, template: '<div ui-view></div>' } ) .state('products', { url: '/products', template: 'products.html' } )
this means can go shop 1 shop 2 using next urls:
http://dom.net/1/products // shop 1 http://dom.net/2/products // shop 2
accordingly, base of operations url of $resource should reflect of route define shop it's accessing:
http://api.net/1/products // products shop 1 http://api.net/2/products // products shop 2
i using next decorator replace resource function each time shop_id in route changes..
.config(['$provide', function ($provide) { $provide.decorator('$resource', ['$delegate', '$rootscope', function($delegate, $rootscope) { var base_url = 'http://dom.net'; var decorator = function (resource_url, paramdefaults, actions) { var resource = $delegate(base_url + '/' + resource_url, paramdefaults, actions); $rootscope.$on('$statechangestart', function(event, tostate, toparams, fromstate, fromparams) { if (fromparams.shop_id != toparams.shop_id) { if (fromparams.shop_id != undefined) { // refresh resource resource = $delegate(base_url + '/' + toparams.shop_id + '/' + resource_url, paramdefaults, actions); } } } ); homecoming resource; }; homecoming decorator; }]); }]);
in $statechangestart event, i'm assign new value resource variable. how come not reflected on instances created?
.factory('product', ['$resource', function($resource) { homecoming $resource('products'); // base of operations url of doesn't alter // if $statechangestart event // triggered within decorator }]);
angularjs
Comments
Post a Comment