I'm dealing with an AngularJS (v1.6) + Restangular (v1.6.1) single page application and I'm struggling to get 2 different Restangular services to work as I expect to.
The idea is to retrieve a list of ProductTypes from the back-end and then a list of Products for each type the final user is allowed to interact with; keep in mind that ProductTypes and Products APIs use different base URLs.
The problem:
the products element transformers are never called: what am I doing wrong?
I tried the following approach:
// index.js file
// here I require everything the web-app needs...
angular.
module('ProductReader', ['ui.router', 'restangular'])
.config(ProductTypesConfig)
.config(Routing)
.service('ProductsRestangular', ProductsRestangular)
.constant('PRODUCT_TYPES_CONST', PRODUCT_TYPES_CONST)
.constant('PRODUCTS_CONST', PRODUCTS_CONST);
// PRODUCT_TYPES_CONST file
PRODUCT_TYPES_CONST = {
API_URL: 'product_types_api',
ENDPOINT: 'product_types'
};
module.exports = PRODUCT_TYPES_CONST;
// PRODUCTS_CONST file
PRODUCTS_CONST = {
API_URL: 'products_api',
TYPES: {}
/**
* here the structure built via the config below should be looking like the following
* TYPES: {
PRODUCT_TYPE_1: {
ENDPOINT: 'product_type_1'
},
PRODUCT_TYPE_2: {
ENDPOINT: 'product_type_2'
}
}
*/
}
module.exports = PRODUCTS_CONST;
// ProductTypesConfig file
/** @ngInject */
function ProductTypesConfig(RestangularProvider, PRODUCT_TYPES_CONST, PRODUCTS_CONST) {
RestangularProvider.setBaseUrl(PRODUCT_TYPES_CONST.API_URL);
//ProductTypes
RestangularProvider
.addElementTransformer(PRODUCT_TYPES_CONST.ENDPOINT, false, function(productType) {
PRODUCTS_CONST.TYPES[productType.name.toUpperCase()] = {
ENDPOINT: productType.endpoint
}
//Products
RestangularProvider
.addElementTransformer(productType.endpoint, false, function(singleProduct) {
let frontEndSingleProductStuff = {};
// ... here stuff is added to the object above...
return angular.extend(rw9Item, {
frontEnd: frontEndSingleProductStuff
});
});
return productType;
});
}
module.exports = ProductTypesConfig;
// Products Custom Factory
/** @ngInject */
function ProductsRestangular(Restangular, PRODUCTS_CONST) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl(PRODUCTS_CONST.API_URL);
});
}
module.exports = ProductsRestangular;
// Routing file
/** @ngInject */
function Routing($stateProvider, PRODUCT_TYPES_CONST) {
$stateProvider
.state('landing', {
abstract: true,
url: '/product-reader',
resolve: {
productTypes: function(Restangular, PRODUCT_TYPES_CONST) {
return Restangular.all(PRODUCT_TYPES_CONST.ENDPOINT).getList();
},
}
})
.state('product-list', {
parent: 'landing',
url: '/list/{:productType}',
resolve: {
productLists: function($transition$, ProductsRestangular, PRODUCTS_CONST) {
return ProductsRestangular.all(PRODUCTS_CONST[$transition$.params().productType].ENDPOINT).getList();
}
}
});
}
from Multiple Restangular services with different run time configurations
No comments:
Post a Comment