June 6th, 2017
5:58 pm
Angular/Ionic–externalising application configuration

Posted under Angular & Ionic & TypeScript
Tags , , , ,

Key Goals

  1. The primary goal is to completely decouple configuration data from the build deployment. This is a key requirement in an enterprise setting, not least because it is vital that the very same build can be tested and signed off in a number of different development and test environments pointing at different server infrastructure.  If a different build was needed for each environment, there is always the risk of an incorrect build, so technically the final production build has never been tested and could break. A good discussion on this may be found on The Twelve Factor App site here.
  2. Upon investigating a pattern for this in Ionic and Angular, I found numerous posts citing different ways around the problem, some appearing quite complex. I was left feeling that this need was not something that had been baked in to the Framework design as a first class citizen – it was certainly not an up front and clear pattern in the documentation. Therefore I wanted a reusable pattern to use as a standard for all my Angular development.
  3. I am using angular-cli with webpack, which is the recommended approach. This produces simple static deployment bundles which are web server agnostic – just an html file which loads one or more js bundles, plus assets such as fonts and images. The pattern for externalising configuration aims to fit in with this and makes no assumptions about the ability to build configuration data dynamically server-side or inject configuration related information into the web server. For example, a common pattern when using Apache Tomcat with Java applications is to inject a configuration location as a JVM parameter into tomcat, which is used later server-side to access the configuration dynamically. We make no assumptions here about the ability to do this kind of trick – any such mechanisms (discussed further below) would be an extension to the pattern for a particular server.
  4. An important goal of the pattern is that it should be testable, i.e. we use dependency injection to inject configuration into the classes that use it, (in our case via a service). This allows unit tests to inject test configuration as required.
  5. The pattern also supports offline use e.g. in an Ionic application. If, as some solutions advocate, the configuration was loaded via an HTTP service in javascript code, this would not work offline with Ionic. The challenge that remains is how and where the configuration would be located in an Ionic deployment, but that is a question for another day and further invesigation.

 

Solution Overview

  1. After a fair amount of investigation I settled on a fairly simple pattern as per this post here. This stackoverflow comment refers to the same technique.  I adapted the technique for my situation – the key points are as follows, and a code sample is shown below.
  2. The basic idea is to load configuration data as a Json object literal from a .js file. This is done by a <script> tag in index.html, prior to the loading of the webpack bundles, which loads the configuration typically as a file from a known location, where the src of the <script> tag is deemed not part of the build.
  3. Whilst this would typically be a location on the same server such as the root directory where index.html is located, it does not have to be, and could equally well be loaded from another server over http. The key point is that the precise src for the script tag is a contract between index.html and any deployment/configuration management software. For example, the configuration file might be dynamically created by Ansible or similar, or the configuration might not be a file at all, and could be dynamically created server side via a web service. These possibilities are all extensions to the basic pattern and depend on the particular web servers and deployment techniques in play.
  4. When running in development mode using ng serve, the bundles are created in memory and no files exist. Therefore this mechanism will not work as the <script> tag will not load anything. We therefore provide a means of having default configuration in the code which will be overridden by the above configuration file if present. If the configuration file is not present (ng serve in dev mode) you will get a 404 for the script tag on the console, which can be ignored.
  5. When running in development mode using files (e.g. via lite-server using  ng build –watch and running lite-server from the dist subdirectory), a config file can be used in the normal way to override the default config if desired.
  6. The default configuration object is exported as a constant from the appropriate environment file, e.g. environment.ts. Whilst there could be default settings in environment.prod.ts, the default is typically set to null in this case so that a configuration file is always used.
  7. The structure of the configuration data is typed via an AppConfig interface which is used everywhere the data is loaded or referenced. In simple cases the configuration data may be just properties of the root AppConfig object. However in more complex cases the object graph could be extensive.
  8. The configuration file loads the configuration object into a global variable which is then read by the AppConfigService, and if present overrides the default configuration. Object.freeze() is used (along with readonly properties on the AppConfig interface) to make the configuration data immutable. Whilst in theory it may be possible to inject the resulting configuration as a constant using a value provider, when I tried this (with the latest Angular 4) I hit a variety of intermittent compile/build errors citing ERROR in Error encountered resolving symbol values statically. In the end I went with an injected configuration service, which consuming classes set up as a getter to allow convenient access.
  9. The AppConfigService loads the global configuration variable via a casted reference to the window object. I tried to get this to work via a declare to reference it as an external object but again I hit compile errors when doing so.

 

Example Code Listings

 

index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Places Admin</title>

<base href=”/”>

<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”icon” type=”image/x-icon” href=”favicon.ico”>

<script type=”text/javascript” src=”appConfig.js”></script>

</head>
<body>
<app-root>Loading…</app-root>
</body>
</html>

appConfig.js – external configuration file.

// Application Configuration
var salientSoft_appConfig = {
  appTitle: "The Places Guide",
  apiBase: "http://localhost:5984/places-guide/",
  messageTimeout: number = 3000
};

environment.ts

// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.

import {AppConfig} from ‘../config/app-config’;

export const environment = {
production: false,
};

export const defaultAppConfig: AppConfig = {
appTitle: ‘The Places Guide’,
apiBase: ‘http://localhost:5984/places-guide/’,
messageTimeout: 3000
};

environment.prod.ts

import {AppConfig} from '../config/app-config';

export const environment = {
production: true
};

export const defaultAppConfig: AppConfig = null;

appConfig.ts – config file interface

/* Root application configuration object
   This encapsulates the global config json properties.
   These must match what is in the actual config file, normally /appConfig.js.
 */
export interface AppConfig {
    readonly appTitle: string;
    readonly apiBase: string;
    readonly messageTimeout: number;
}

app-config.service.ts

import {Injectable} from '@angular/core';
import {AppConfig} from './app-config';
import {defaultAppConfig} from '../environments/environment';

@Injectable()
export class AppConfigService {
private _appConfig: AppConfig;
buildConfig(): AppConfig {
const appConfig: AppConfig = (<any>window).salientSoft_appConfig || defaultAppConfig;
return Object.freeze(appConfig);
}
constructor() {
this._appConfig = this.buildConfig();
}
get(): AppConfig {
return this._appConfig;
}
}

app.component.ts – example configuration consumer

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

constructor(
private appConfigService: AppConfigService
) {}

public get appConfig(): AppConfig {return this.appConfigService.get(); }

ngOnInit(): void {
document.title = this.appConfig.appTitle;
}

No Comments »

March 10th, 2017
11:02 am
Styling and Theming an Ionic Application

Posted under Ionic
Tags , , ,

This isn’t obvious when you browse the documentation, at least when starting out.

I’m coming from having used for example ThemeRoller with PrimeFaces, where structural css is defined by the components, to give size, shape, layout etc. Theming css   is defined by the theme, using common style classes etc. used by all components, to give colours, textures and fonts etc. The two concepts are mutually orthogonal, so you can use any theme with any component, and create your own theme.

I’ve seen theming and themes mentioned on a number of Angular/Ionic related sites, but without the same concept of orthogonality – themes are mentioned along with specialised components which are deemed to be part of a theme. Therefore, theming in Angular appears to encompass more than just the look and styling of components, but also the actual components and their functionality.

This could be summarised simply as follows:- ThemeRoller encompasses the look of an application, with components such as Primefaces encompassing the feel of the application.

With Angular/Ionic, the concept of theming is broader and appears to encompass both look and feel.

 

Some excellent posts by Josh Morony on how to theme an ionic application help to get under the hood on all this, and are available here:-

https://www.joshmorony.com/a-guide-to-styling-an-ionic-2-application/

https://www.joshmorony.com/a-list-of-common-css-utility-attributes-in-ionic-2/

https://www.joshmorony.com/tips-tricks-for-styling-ionic-2-applications/

https://www.joshmorony.com/hacking-css-in-ionic-2/

No Comments »

March 10th, 2017
10:26 am
Navigation Techniques in Ionic vs Angular2

Posted under Ionic
Tags , , ,

Whilst Angular 2 routing is handled via routers, Ionic takes a different approach with the use of the NavController and related components based on it like Nav and Tab.

Ionic navigation allows views to be pushed and popped from a navigation stack, and allows a root page to be established for a particular navigation stack.

A useful tutorial on Ionic Navigation may be found here.

No Comments »

March 4th, 2017
1:05 pm
Configuring Ionic 2 with Webstorm for development/debugging

Posted under Ionic
Tags ,

Having already configured Angular 2 with Webstorm  here, this post details the steps to get Ionic working in similar fashion, to be able to run and debug an ionic application running in a browser. The use of an android emulator/ a real android (and then IOS) will be dealt with later.

  1. First install Ionic 2 as detailed similarly either here or here.
  2. Next, configure Webstorm as detailed in this post here. Note that the first step adds a phonegap/cordova plugin which allows Ionic serve to be started within Webstorm, without using a separate command window. This trick is similar to step 10 in this post which does the same thing for angular 2/npm start. Note that I had to dig around for the phonegap/cordova executable – in my case it was a command/batch file located at C:/Users/SteveW/AppData/Roaming/npm/ionic.cmd , and note that Webstorm did require the .cmd extension explicitly to work. Per the instructions, ensure you select serve as the command and at this stage browser for the platform.
  3. The second step in the post configures a Javascript Debug configuration. Enter the name and the target URL. Note that in order to get breakpoints to be obeyed, I had to add an entry in the Remote URLs of local files section. In my case I just added the same url as at the top, against the top level project folder which was already shown. Prior to this, I could set a breakpoint successfully (meaning I did not have any sourcemap issues like the ones I hit with vs code here), but the breakpoint was not obeyed. Once I added the remote URL everything worked.

No Comments »