Pass environment variable through to Angular app - angularjs

I'd like to configure my gulp webserver task to pass an environment variable into the angular app. Each team member has his own VM running the API and the variable would instruct the Angular app of the base API url. I'm trying to eliminate the need for every team member to remember to edit the config file after every TFS update.
I thought of simply setting a response header via middleware, but javascript cannot see response headers for the current page - only those of XHR responses.
So I try initializing the config service by performing a HEAD request against the web root, but this requires resolving a $http promise which requires adding a resolve to the route config to ensure it gets resolved before something tries to use it.
I tried just injecting a cookie via middleware and reading it with the $cookies service, but Internet Explorer apparently doesn't see 'localhost' as a valid domain name for cookies and does not read them.
So what other ways are there to allow an environment variable (or other form of local config) to be passed into the angular app?

We have solved this problem in many ways for different situations.
We don't use the base URL but just relative "/folder/resource".
We have an HttpHandler that resolves files with custom extension i.e. ".xyz". Then we have a file named "config.xyz" which is just a JavaScript file with something like:
{
baseUrl: [BASE_URL]
}
When the handler is asked to provide this file, the handler reads the file and does the replacements and then serve its content.
Use the one fake name for the server that serves the API. I.e: thisismylocalfake and then ask developers to configure their hosts file in system32
Have a gulp tasks that, when you compile the application, takes one config.js file and uses the machine name to replace a tag like in option 2.

I ended up adding middleware to the gulp-webserver to intercept a request for our config service file. Then I used gulp-replace and gulp-respond to inject the url from the environment variable directly in the stream. No files edited, technically and it works without having to have any sort of dev-specific code in the project.

Related

How to setup api,s in react native template

I have a react native app (chat) template which I cant figure out how to set it up, don't know if am to get an api key from cometchat or use firebase. The template has been preconfigured I think and by adding firebase credential in the env. the login and register page works, but the chat section is blank.
This is what the documentation says:[
API Integration
Doot react having fake-backend setup already. you will find all files related to API integrations in the src/API folder.
src/apiCore.ts file contains axios setup to call server API(s) including get, put, post, patch, delete, etc methods, interceptors & token set methods.
src/index.ts file contain all module's API call functions which are exported from each module's individual .ts file, E.g. contacts.ts, bookmarks.ts etc.
src/urls.ts file contain all module's API's url.
Note : we have added a Fake backend setup just for user interactions, but if you are working with the real API integration, then there is no need of fake backend as well as the fakeBackend file located in src/helpers/fakeBackend.ts, so you can delete it and also remove the code related to fakeBackend from app.tsx file. you just need to update API's url of the related module from src/apiCore/urls file, that's it!}
The chat interface after login:
App documentation:
App documentation:

Blocking / Initialization service with angular.js

My apps are using many web services on the intranet, and url-s for those depend on the server environment.
My apps are hosted on IIS, which adds an HTTP response header like this: Environment: DEV, so every web app knows in which server environment it is running, and thus which intranet servers it must use to call all the services.
Each of my angular apps uses a service that issues a simple GET against the app's own root just to get any response with the environment name in it, and set configuration accordingly.
Question:
How should an angular app implement such a service that would execute as the very first thing in the application, and make sure that while it is getting that first response, nothing in the app tries to execute an HTTP request against other services, or even try to use any configuration provided by my environment service?
Is there a way to implement such a service in angular that could block every other service / factory in the application till it is done initializing itself?
I have many other services in the app, and none of them really know what to do till my environment service has finished its initialization.
UPDATE
Looking at it from another angle.... is it possible to implement such an interceptor in angular that could do the following?:
execute an HTTP request and block the app's execution till it gets a response
make information from the response available throughout the app as a service/factory/config.
Angular lifecycle could be one solution. Using the angular.config() phase you could peek at the headers of the HTTP service.
Create a factory called 'httpInterceptor'
function httpInterceptors(siteConfig, $q, $injector) {
return {
response: function(data, status, headers) {
siteConfig.setEnvironment(headers['Environment']);
return data;
}
};
)
Then in angular.config()
$httpProvider.interceptors.push('httpInterceptor');
If you truly want to block the other option is to use UI router resolve property to block routes loading until the request has been made https://github.com/angular-ui/ui-router/wiki you can add the resolve method to the root state.
Resolve
You can use resolve to provide your controller with content or data that > is custom to the state. resolve is an optional map of dependencies which > should be injected into the controller.
If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.

How to access config/env/all.js data in a client controller?

I have some configuration values(numbers) that I need while doing some computation in the angular code in the client controller. I general, how can one access the serverside config data in the clientside code?
If note is it possible to have a config file/folder in the public folder and easily access using angular code in client controller?
I'm not 100% sure what you are looking for here, but you have basically 3 options to handle this.
Expose An API Endpoint
You should be able to simply create an API endpoint to read the config data on the server and send it down to the client as JSON. Then you could access it in Angular like so:
$http.get('/api/config')
.success(function(configData){
//Do something with config data
});
Expose Config File Publicly
Warning - This may not be wise if your config contains sensitive data such as connection strings.
If you have a .json or a .xml file on the server with this info, then you could just make it available to HTTP GET requests and then the same code as above would apply. With the exception that if it is XML you will need to add a transform to parse the data.
$http.get('/config.json')
.success(function(configData){
//Do something with config data
});
Embed Config As Angular Constant/Value
Note - This won't work if your data is dynamic on the server.
An even simpler way is to simply put your configuration into a .js file and register it with Angular as a constant or a value.
angular.module('myModule')
.constant('config', {
foo:'bar',
blah:123
});
This way you can simply inject that anywhere in your app that you need access to it.

Send data to a front-end application via node?

I have a node application that is hosting a self-contained front-end application in /public and a rest api. The front-end application communicates to the back-end exclusively via REST, but now I need to send some basic configuration information on the initial application load.
Rather than make an ajax request when the page loads, I would like to send down the required config information when /index.html is requested since it is necessary for the application to run.
What's the simplest way to setup some basic config?
Is there a way I can serve some script via node, and then parameterize it from the server?
Something like
/scripts/config.js
angular.constant('value1', '#{some parameterized server value}');
I'm using express.
You can just add a route that serves up the config.
Something like.
app.get('/scripts/config.js', function(req, res) {
var content = 'angular.module(\'config\', [])\n';
content += ' .constant(\'value1\', ' + someValue + ')';
res.set('Content-Type', 'text/javascript');
return res.send(content);
}
The only way to do it without making an Ajax request is include a config.json file in your index.html You can have node reading/writing your configuration properties to this file.
The order of execution in Angular is:
app.config()
app.run()
compile functions for directives
app.controller
directives linking
You can put your kickstarting logic in app.config() or app.run().
I believe, the best practice though is separate your config logic in a module and use $http to fetch the properties dynamically.

Appending Param to AngularJS REST Queries

I'm using AngularJS with UI-Router and am attempting to attach a query parameter to a url on all http requests across my site.
I have an OAuth system on the backend and was previously applying Authorization headers to all requests, however to preserve backwards compatibility - have discovered I will have to instead apply a url parameter with the user identification to the backend.
My issue is that, I cannot use $httpInterceptor in the config portion of the app, because at that point in the app I don't have the current User, and can't inject $http to resolve the current user because that creates a circular dependency.
I was trying to use $http.defaults.transformRequest in the run portion of the app, but that didn't seem to be able to append a parameter to the url.
Is there a way to do this short of hand writing it on every REST request across the app?
I had similar problem in my current project.
To solve the problem I manually request current user info before app bootstapping & store it in localStorage.
Then bootstrap the app & in the config section you will have accesss to current user info.
TIP: to get user info before app bootstrap you can still use $http service by manually injecting it:
angular.injector(['ng']).get('$http');

Resources