Configuring multiple Restangular services with unique runtime settings

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();
        }
      }
    });
}

Answer №1

Two different Restangular API URL services can be set up in a configuration like the following:

factory("service1", ["Restangular", function(restangular) {
  return restangular.withConfig(function(RestangularConfigurer) {

    RestangularConfigurer.setBaseUrl("http://localhost:8090/apiws");

  });

}]);


factory("service2", ["Restangular", function(restangular) {
  return restangular.withConfig(function(RestangularConfigurer) {

    RestangularConfigurer.setBaseUrl("http://localhost:8080/api");
    RestangularConfigurer.setDefaultHeaders({
      "Authorization": "Basic 123345667",
    });

  });

}]);

To learn more, refer to the Official documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Ionic for local data retention

Seeking assistance with connecting my app to local storage in order to save data on the user's device without resetting every time the app is closed. Struggling to link local storage to an array of objects. Any guidance would be highly appreciated. Re ...

styling multiple elements using javascript

Recently, I created a jQuery library for managing spacing (margin and padding). Now, I am looking to convert this library to pure JavaScript with your assistance :) Below is the JavaScript code snippet: // Useful Variables let dataAttr = "[data-m], [d ...

The OOP functionality in Three.JS seems to be malfunctioning, as certain elements are not being properly accessed and displayed

I've run into some issues while trying to implement OOP in my Three.js project. The original script displays three y-rotational planes, but it seems like some objects I've created aren't being called when I check the console. Can someone ple ...

Ways to render component solely based on the alteration of the class props

In my ReactJS project, I am fetching JSON data from a RESTful Django host and using it to create a table with filters. Here is my Table class: class MainTable extends React.Component { constructor(props) { super(props); this.state = { res ...

Filtering data in Laravel can be efficiently achieved by utilizing Laravel's ORM hasmany feature in conjunction with Vue

Hey there, I'm currently working with Laravel ORM and Vue 2. I've encountered some issues with analyzing Json data. Here's my Laravel ORM code: $banner = Banner::with('banner_img')->get(); return response()->json($banner); ...

Renovating code structure in JavaScript

As I develop a small application that interacts with a database, I have opted to use Promises instead of the callback pattern for simplicity in my code. Through my coding experience, I've noticed a recurring pattern in my logic and I'm seeking ad ...

Horizontal Panning Feature for D3 Horizontal Bar Charts

I am working on a D3 Bar Chart and I would like it to have horizontal panning functionality similar to this example: https://jsfiddle.net/Cayman/vpn8mz4g/1/. However, I am facing an overflow issue on the left side that I need to resolve. Below is the CSV ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

What is the process for setting a default value in an array using Angular and then showcasing that value in a textbox?

I have been working on creating a form that includes a feature to dynamically append new rows. While I am able to successfully create new rows dynamically, I am facing an issue with displaying the initial values in my textboxes. Below is a snippet of my c ...

When JSONP is used in cross-domain AJAX calls, it retrieves plain JSON data

I am facing an issue with an API that I need to integrate. The API provides JSON data, but as it involves a cross domain AJAX call, I have to utilize jsonp. $.ajax({ type: "GET", url: url + query, ...

The static folder in Express server is failing to serve files

I have an application with certain static files that I want to send to the client, however the server is not sending them. app.use(express.static(__dirname, '/public')); I need help fixing this particular code snippet. ...

Challenges experienced during the process of uploading a website to the server

I seem to have encountered an issue where the Navigation background image is missing after uploading my website onto the server. Surprisingly, everything else seems to be working perfectly. What could possibly be the cause of this discrepancy? navbar-de ...

Automatically navigate to a different page using JavaScript after 5 seconds without interrupting the execution of other code

Is there a way to redirect to a specific URL after 5 seconds without halting the execution of other code on the page? I want all the other code to run first before triggering the redirection. Wrapping the entire page in a setTimeout block is not an option. ...

javascript pull data from an array

As a novice in HTML and JavaScript, I have a brief code snippet that embeds multiple audio files. I am utilizing a loop and would like to utilize strings from an ARRAY as the sources for the WAV files (rather than just "file1.wav"). Thank you. <!DOCT ...

Exploring arrays by filtering through various options chosen in a dropdown selection

I'm currently in the process of developing a search tool that utilizes the chosen options from a dropdown menu to search through an array associated with those selections and then displays a value on the HTML. I've been attempting to implement a ...

Can you explain the purpose of using double colons before an expression variable in AngularJS?

Can you explain the use of double colons :: preceding an expression variable in AngularJS? Additionally, how does {{ firstName }} differ from {{ ::firstName }}? ...

Can you explain the contrast between onsubmit="submitForm();" and onsubmit="return submitForm();"?

Is it possible that the form below is causing double submissions? <form name="myForm" action="demo_form.asp" onsubmit="submitForm();" method="post"> function submitForm(){ document.myForm.submit(); } I've noticed a bug where sometimes two ...

What are the best practices for effectively testing directives that involve DOM manipulation?

My inquiry begins with a preliminary question: Is it advisable to perform unit testing on DOM manipulation within Angular directives? Consider, for example, the following cohesive linking function: function linkFn(scope, element) { var ribbon = eleme ...

What prevents variables defined in outer blocks from being accessed by nested describe() blocks?

In my real code, I encountered a problem that I wanted to demonstrate with a simple example. The code below functions properly. I defined a variable in the root describe() block that can be accessed in the it() blocks of nested describe()s. describe(&apo ...

Using node.js to download files with axios, streaming the content, and then

I am attempting to download a PDF file using axios, and save it on the server side using fs.writeFile. My code is as follows: axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => { fs.writeFile('/temp/my ...