Set up AngularJS application to save API URLs

In configuring my API endpoint and URL's, I utilize a custom app.config.js file with environment variables:

angular.module('api-config', []).constant('ENV',
{
    name: 'My Project Name',
    apiEndPoint: 'http://SOMEIP/gateway/',
    apiListUser: '/user',
    apiUser: '/user/{:id}'

});

Controller

var servicePath = ENV.apiEndPoint;
var listUserApi = ENV.apiListUser;

return $http({
    method: 'POST',
    url: servicePath + listUserApi
})

Challenges faced by the current approach:

  1. External developers or consultants gain access to private configuration data stored in the config.

  2. Limited scalability due to fixed configuration preventing dynamic scaling and application customization during deployment.

Goals for improvement:

  • Deploying AngularJS applications in various environments (staging, production) with different configurations without altering the code.
  • Sharing AngularJS application code externally while protecting confidential details by separating all configuration in a distinct app.config.js file. Is this the most secure method?
  • Avoiding exposure of API endpoints and URLs in the app.config.js file to any developer viewing the source code. How can this be prevented?

Answer №1

Our approach involves utilizing a configuration file (e.g., app.config, defaults.config) within our application architecture. Upon launching the application, we make a call to a web API that retrieves the information from this config file in JSON format. Subsequently, we store this data in a dedicated service, enabling us to access all configuration settings through an angular service. This method effectively addresses the issues you raised.

Answer №2

<!DOCTYPE html>


<html lang="en" ng-app="app">

<head>
  <meta charset="UTF-8>
  <title>Test</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="config.js"></script>
</head>

<body ng-controller="myCtrl">
  {{configData.key1}}

  <script>
    (function() {
      var app = angular.module("app", [])


     .run(['urlFactory', function(urlFactory) {
        urlFactory.getConfig(window.__env);
      }])

      .controller("myCtrl", function(APIFactory, urlFactory, $scope) {
        
        $scope.configData = urlFactory.configData;
        APIFactory.proveAPIfactHaveData();
        

      }).factory("urlFactory", function() {

        var configData = {
          key1: null,
          key2: null
        };

     
         function getConfig(data) {
          angular.extend(configData, data);
        }

        var service = {
          configData: configData,
          getConfig: getConfig,
        }
        return service;

      }).factory("APIFactory", function(urlFactory) {

        var service = {
          proveAPIfactHaveData: proveAPIfactHaveData,
        }
        return service;

        function proveAPIfactHaveData() {
          alert(JSON.stringify(urlFactory.configData));
        }

      });
    }());
  </script>


</body>

</html>

your config.js file

(function (window) {
  window.__env = window.__env || {};
    window.__env.key1       =   "key1";
    window.__env.key2       =   "key2";
}(this));

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

The code generated by Asto SSR may not be compatible with older iOS versions, causing it to fail to run

I have been running my astro SSR site on Netlify with great success. However, I recently encountered an issue when testing it on older iPhone models like the iPhone 6 and earlier. It seems that all script executions halt, rendering the site non-interactive ...

Using Vue.js to iterate over a list of items and accessing specific array objects by their unique identifier

My JSON array of objects has the following structure: https://i.sstatic.net/1IUVE.png When generating a <ul>, I need to fetch an ID from an API for each <li>: <ul> <li v-for="genre in movie.genre_ids"> {{ genre }} ...

"Encountering an error in Vue.js when trying to dynamically access nested arrays: push function not

My goal is to have two buttons displayed when a user uploads data: one for old products and one for new products. When the user clicks on either button, the corresponding products will be uploaded as 'old_product' or 'new_product'. Howe ...

Using React router to handle multiple hierarchical parameters

Having a documentation component in my app, I want the URLs to appear as follows: url: myapp.com/docs url: myapp.com/docs/document-1 url: myapp.com/docs/category-1/document-2 url; myapp.com/docs/category-1/category-2/document-2 The challenge lies in set ...

Implement a feature in JS/HTML where clicking on a button shifts a specific section of a row from one table to another while simultaneously deleting the remaining

I am facing an issue with two tables - addFriends and existingFriends. The addFriends table contains a button in the fourth column, which, upon clicking, should delete the corresponding row from that table and add it to the existingFriends table. Currentl ...

Is it possible to implement the SCSS CSS preprocessor in Angular 1.6.6, even though it is already utilizing LESS as the current CSS preprocessor?

Is it necessary to compile SCSS and Stylus files into CSS before importing them into my Angular version 1 app? Are there any other alternatives available? Context: I have two applications, one using Angular 4 with SCSS and the other using Angular 1 with L ...

What is the importance of manually merging geometries?

After exploring the performance implications of merged geometries, I've discovered that the GPU generates draw calls for all shared geometries combined with materials (or maybe just the material count). This has led me to wonder why developers are req ...

Guide on efficiently inserting multiple records into a MySQL database using Node.js and also implementing a check to insert only when the record does not already exist

I need to add numerous records to a table while also checking for duplicates to ensure that only new records are inserted. I have successfully inserted a single record by checking for duplicates using the code below. connection.query(` INSERT INTO pla ...

Detecting changes to DOM elements without using jQueryResponding to DOM element

Suppose I have the following HTML structure: <div id='content'></div> I want to receive an alert when there are height mutations on this element. I thought about using the MutationObserver class for this, but I encountered a specifi ...

Adding dynamic elements in Ionic2 and AngularJS can be achieved by using the correct syntax and functions provided

I am looking for a way to allow users to add elements like user inputs using ionic2/angular. In a scenario where I would typically use the following code in normal JS: function addDestination(){ var destDiv = document.getElementById('destPlac ...

iOS is not receiving JSON data in the response headers

I am currently utilizing the CocoaHTTPServer for establishing my server connection. However, I encountered an issue with retrieving JSON data in the header file of my HTML page (web client). Here is the code snippet : HTML Page : endAPSession: funct ...

Retrieving checkbox values from HTML and storing them in a temporary JavaScript/HTML variable

My form has multiple checkboxes all with the same id "cbna". When I submit the form, I want the JavaScript code to check if at least one checkbox is checked. If no checkbox is checked, an alert should appear. If a checkbox is checked, the value stored in ...

Is it possible to generate an array of all matches found by a regular expression

I am trying to utilize the match-all package in order to match CSS selectors and generate an array of all of them. Here is the code snippet. const matchAll = require("match-all"); let s = `.u-br, .u-nr { blah blah } .u-tr { blah .blah }`; consol ...

Unlocking the potential of Arrays in Javascript: strategies for extracting maximum value

After running a database query in node, I received the result in the form of an object: [ [1234] ]. Now, I am trying to extract this value and convert it into a string so that I can pass it onto the client side. Although I have written the necessary code ...

Locate a JQuery element within another JQuery element

Apologies for my poor grasp of English. I am working with HTML and JavaScript. <noindex> <h1>This is h1 in noindex</h1> <div> <h1>This is h1 in noindex and in div</h1> <div> <h1>This is h1 in noindex a ...

Effortless method for distributing NPM-loaded modules among various Browserify or Webpack bundles

Feeling frustrated trying to find a straightforward way to share code, required via NPM, across multiple Browserify or Webpack bundles. Is there a concept of a file "bridge" that can help? I'm not concerned about compile time (I know about watchify), ...

Verify if an element with a specific index exists within an array

$.each(constructions, function(i,v) { if ($.inArray(v.name, map[ii].buildings) == -1) {//do something} }; In this scenario, the constructions array consists of unique objects with a name attribute. On the other hand, map[ii].buildings is an array contain ...

Angular 2: Harnessing the power of dynamic backlinks on landing pages!

I am facing an issue with my Angular 2 item page. When a user lands on the page via a deep link, the Location.back() function does not work as there is no history in the Location object. To address this, I attempted to use a workaround where if the back() ...

The Reactjs application is failing to display the real-time data produced by the state

I am encountering an issue with looping through a JavaScript array of objects on a ReactJS component. Upon inspecting the Chrome browser console, the following output is displayed from console.log --- 0: {id: 1, title: "This is a post 1"} 1: {id: ...

Prevent dragging of the div element that includes the "XYZ" class

I could really use some assistance as I am still learning j Query and Angular. I have a Div that serves as a container for another Div, and I am looking to prevent dragging on the Div with the class XYZ ...