I'm currently working on a single page application using AngularJS (v1.6) along with Restangular (v1.6.1), but I'm facing some challenges with getting two separate Restangular services to function as intended.
The main objective is to fetch a list of ProductTypes from the backend and subsequently retrieve a list of Products for each type that the end user can interact with; it's important to note that the ProductTypes and Products APIs have distinct base URLs.
The issue at hand:
the element transformers for products are not being triggered: what could be causing this problem?
I experimented with the following method:
// index.js file
// importing necessary modules...
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: {}
/**
* structure based on configuration should resemble the below
* 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 = {};
// ... add stuff 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();
}
}
});
}