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

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.

Related

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.

Pass environment variable through to Angular app

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.

Accessing Session values in Angular.js

I am unable to access the session values which is set by node.js in Angular.js controller. I am using the Express framework. How to resolve it? Here is my code.
app.use(express.cookieParser());
app.use(express.session({
secret: '1234567890QWERTY',
cookie: { httpOnly: false }
}));
//setting the values
cookies.set('username',username);
req.session.username=username;
Presumably you want to do something like show the username in your angular app. As I mentioned in this answer, the hard part to Angular is not thinking about what data the server has, but thinking about data the server should provide to the browser via API.
My general model is to have the angular page start up without any data and have a low-level controller invoke a service (say AuthenticationService or IdentityService) that requests relevant data from the server, e.g. HTTP GET /api/identity. That will return a block of JSON that the page can then store in that low-level controller. Any deeper controller can then access the identity (or whatever) data loaded in that first request.

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.

CXF. Is it possible to log the request/response XML without using Interceptor?

I would like to get the request XML in my Web service method and would like to save it. I know I can use LoggingInInterceptor to do that. However, I do not want to use it. The reason is when I save the request XML, I would like to perform user validations, get the client name and use the client name as the File name to save it.
Is there a way I can get the request XML in my Web service method.
No, you cannot. But you can write a generic HTTP service which gets the text content of a request.

Resources