Angular 2: Bootstrap Accordion in Angular 2


The accordion component builds on top of the collapse directive to provide a list of items, with collapsible bodies that are collapsed or expanded by clicking on the item’s header.

Base specifications: bootstrap 3 or bootstrap 4


This content is straight in the template.
I can have markup, too!


  1. <p>
  2. <button type=“button” class=“btn btn-primary btn-sm”
  3. (click)=“group.isOpen = !group.isOpen”>Toggle last panel
  4. </button>
  5. <button type=“button” class=“btn btn-primary btn-sm”
  6. (click)=“status.isFirstDisabled = ! status.isFirstDisabled”>Enable / Disable first panel
  7. </button>
  8. </p>
  10. <div class=“checkbox”>
  11. <label>
  12. <input type=“checkbox” [(ngModel)]=“oneAtATime”>
  13. Open only one at a time
  14. </label>
  15. </div>
  17. <accordion [closeOthers]=“oneAtATime”>
  18. <accordion-group heading=“Static Header, initially expanded”
  19. [isOpen]=“status.isFirstOpen”
  20. [isDisabled]=“status.isFirstDisabled”>
  21. This content is straight in the template.
  22. </accordion-group>
  23. <accordion-group *ngFor=“let group of groups” [heading]=“group.title”>
  24. {{ group?.content }}
  25. </accordion-group>
  26. <accordion-group heading=“Dynamic Body Content”>
  27. <p>The body of the accordion group grows to fit the contents</p>
  28. <button type=“button” class=“btn btn-primary btn-sm” (click)=“addItem()”>Add Item</button>
  29. <div *ngFor=“let item of items”>{{item}}</div>
  30. </accordion-group>
  31. <accordion-group #group [isOpen]=“”>
  32. <div accordion-heading>
  33. I can have markup, too!
  34. <i class=“pull-right glyphicon”
  35. [ngClass]=“{‘glyphicon-chevron-down’: group?.isOpen, ‘glyphicon-chevron-right’: !group?.isOpen}”></i>
  36. </div>
  37. This is just some content to illustrate fancy headings.
  38. </accordion-group>
  39. </accordion>



import { AccordionModule } from 'ng2-bootstrap/ng2-bootstrap';
// or
import { AccordionModule } from 'ng2-bootstrap/components/accordion';


// component Accordion
  selector: 'accordion',
  template: `<ng-content></ng-content>`
export class AccordionComponent {
  @Input() public closeOthers:boolean;

  public addClass = true;

// component AccordionGroup
  selector: 'accordion-group',
export class AccordionGroupComponent implements OnInit, OnDestroy {
  @Input() public heading:string;
  @Input() public panelClass:string;
  @Input() public isDisabled:boolean;

  @Input() public get isOpen();

  // should be inside of Accordion element
  constructor(private accordion:Accordion) {}

Accordion properties

  • closeOthers (?boolean=false) – if true expanding one item will close all others

Accordion Group properties

  • heading (?string='') – clickable text in accordion’s group header, check accordion heading below for using html in header
  • isOpen (?boolean=false) – is accordion group open or closed
  • isDisabled (?boolean=false) – if true disables accordion group
  • panelClass (?string='panel-default') – provides an ability to use Bootstrap’s contextual panel classes (panel-primary, panel-success, panel-info, etc…). List of all available classes link

Accordion heading

Instead of the heading attribute on the accordion-group, you can use an accordion-heading attribute on any element inside a group that will be used as the group’s header template.

Properties parser


A parser for .properties files written in javascript

A parser for .properties files written in javascript. Properties files store key-value pairs. They are typically used for configuration and internationalization in Java applications as well as in Actionscript projects. Here’s an example of the format:

# You are reading the ".properties" entry.
! The exclamation mark can also mark text as comments.
website =
language = English
# The backslash below tells the application to continue reading
# the value onto the next line.
message = Welcome to \
# Add spaces to the key
key\ with\ spaces = This is the value that could be looked up with the key "key with spaces".
# Unicode
tab : \u0009

(taken from Wikipedia)

Currently works with any version of node.js.

  • parse(text): Parses text into key-value pairs. Returns an object containing the key-value pairs.
  • read(path[, callback]): Opens the file specified by path and calls parse on its content. If the optional callback parameter is provided, the result is then passed to it as the second parameter. If an error occurs, the error object is passed to callback as the first parameter. If callback is not provided, the file specified by path is synchronously read and calls parse on its contents. The resulting object is immediately returned.
  • createEditor([path][, options][, callback]]): If neither path or callback are provided an empty editor object is returned synchronously. If only path is provided, the file specified by path is synchronously read and parsed. An editor object with the results in then immediately returned. If both path and callback are provided, the file specified by path is read and parsed asynchronously. An editor object with the results are then passed to callback as the second parameters. If an error occurs, the error object is passed to callback as the first parameter. The following options are supported:
    • options.separator: The character used to separate key/values. Defaults to “=”.
    • options.path: Treated the same way as the optional path argument. If both are provided the arguement wins.
    • options.callback: Treated the same way as the optional callback parameter. If both are provided the arguement wins.
  • Editor: The editor object is returned by createEditor. Has the following API:
    • get(key): Returns the value currently associated with key.
    • set(key, [value[, comment]]): Associates key with value. An optional comment can be provided. If value is not specified or is null, then key is unset.
    • unset(key): Unsets the specified key.
    • save([path][, callback]]): Writes the current contents of this editor object to a file specified by path. If path is not provided, then it’ll be defaulted to the path value passed to createEditor. The callback parameter is called when the file has been written to disk.
    • addHeadComment: Added a comment to the head of the file.
    • toString: Returns the string representation of this properties editor object. This string will be written to a file if save is called.

The easiest way to get node-properties-parser is with npm:

npm install properties-parser

Alternatively you can clone this git repository:

  • Xavi Ramirez

This project is released under The MIT License.

properties reader in node js


Properties file reader for Node.js

An ini file compatible properties reader for Node.JS


The easiest installation is through NPM:

npm install properties-reader

Or clone the repo and include the /src/PropertiesReader.js script.


Read properties from a file:

var PropertiesReader = require('properties-reader');
var properties = PropertiesReader('/path/to/properties.file');

The properties are then accessible either by fully qualified name, or if the property names are in dot-delimited notation, they can be access as an object:

// fully qualified name
var property = properties.get('');

// by object path
var property = properties.path();

To read more than one file, chain calls to the .append() method:


To read properties from a string, use the .read() method:' = Value \n = Another Value');

To set a single property into the properties object, use .set():

properties.set('', 'Property Value');

When reading a .ini file, sections are created by having a line that contains just a section name in square brackets. The section name is then prefixed to all property names that follow it until another section name is found to replace the current section.

# contents of properties file
some.thing = foo

some.thing = bar

// reading these back from the properties reader
properties.get('main.some.thing') == 'foo';
properties.get('blah.some.thing') == 'bar';

Checking for the current number of properties that have been read into the reader:

var propertiesCount = properties.length;

The length is calculated on request, so if accessing this in a loop an efficiency would be achieved by caching the value.

When duplicate names are found in the properties, the first one read will be replaced with the later one.

To get the complete set of properties, either loop through them with the .each((key, value) => {}) iterator or use the convenience method getAllProperties to return the complete set of flattened properties.

Data Types

Properties will automatically be converted to their regular data types when they represent true/false or numeric values. To get the original value without any parsing / type coercion applied, use properties.getRaw('').


If you find bugs or want to change functionality, feel free to fork and pull request.



angular 2 spring boot application

Angular2Boot is in sync with Angular 2.0.0, see the Angular release notes !

LATEST NEWS ! Angular2Boot will be presented at JavaOne 2016 this year ! We hope to meet your there and discuss with you !

Angular2Boot is an opiniated framework to build web applications in Java 8. It is built upon rock-solid foundations : Angular 2, GWT and Spring Boot. You can of course use it with any Java backend, like JavaEE with JAX-RS Web services or whatever else.

It provides a very effective way to build Single Page Applications. The development mode is iterative and quick (live code reload), with the strongly typed qualities of Java and the functionalities brought by modern IDEs. The produced code is easy to deploy (relying on one jar only), robust (runs on the JVM) and optimized (Angular 2 change detection and GWT optimized compilation).

Build a starting application in less than 5 minutes and enter into the details to get most of Angular2Boot !

Here is a presentation video (in French) of how it works, at the Toulouse Angular User Group in June 2016.

Summary of this document

How to build an application from the official archetype ?

Use the archetype which builds a fully working Angular2 + SpringBoot application :

mvn archetype:generate \
  -DarchetypeGroupId=fr.lteconsulting \
  -DarchetypeArtifactId=angular2-gwt.archetype \

Note about the version : you can use either the latest release version like in the example above, or the next snapshot version (1.6-SNAPSHOT in this case) and benefit from the latest improvements and bug fixes. Features only available in the snapshot version are marked in the documentation. You can expect a new release few days after new features are tested and validated.

Enter the desired groupId, artifactId, version and package and your application will be created in a sub directory named after the choosen artifactId.

Enter into this directory and build your application :

mvn clean install

Everything should work fine. Now you can run the built application with this :

java -jar target/YOUR_ARTIFACT_ID.jar

This will launch the SpringBoot application with a minimal client side Angular 2 controller. When entering http://localhost:8080 in your browser, a page should load and show a “Your application is working !” message. This is the sign that everything has been bootstraped correctly and that you can begin to work. There is also an input box, if you change its content the previous title will change too. That’s shows that the two-way Angular data binding is working in your application !

Development mode

During development, building the entire application is too time-consuming. In order to save your time, you can stop the java process we just launched and launch the SpringBoot development mode instead :

mvn spring-boot:run

This will allow to have hot swapping of classes on the server side (to a certain extent, see documentation).

You may also want to hot reload client classes when you change them. In this case you need to start the GWT Super Dev Mode. But that has to be done in another terminal because we don’t want to stop the Spring Boot server !

mvn gwt:run-codeserver

You can open the application project in your IDE (see the chapter on configuration problems that can happen), work on the code and refresh in the browser to get live updates.

And now, what’s next ?

Now that you have a working boostrapped application, you can either continue reading to get more details about what is inside the application you just created. Or you can jump into the Tour of Heroes tutorial to learn the basic concepts of Angular 2 and about creating an Angular2Boot application.

You can also read the cookbook to learn advanced and deepened techniques.

Typically you will want to :

  • add new Angular components to your application. Use the Angular documentation and the Angular2Boot reference below.
  • add new REST services on the backend with SpringBoot,

Anatomy of the generated project

The project you have just built contains already several components. If you inspect the pom.xml file, you will see that the project inherits from spring-boot-starter-parent which is a way to bootstrap a SpringBoot application. The main dependencies your project has are :

  • spring-boot-starter-web: just enough Spring Boot to serve static files and REST services.
  • gwt-user and gwt-dev: GWT runtime and compiler, needed to compile the front side of the application.
  • angular2-gwt: Angular 2 bindings and tools for GWT.

Regarding the project build, only two plugins are used: gwt-maven-plugin and spring-boot-maven-plugin.

Static resources are served from the src/main/resources/static directory. You can add more files there and they will be then accessible from the browser.


Appart from all the .js files which are the required runtime scripts, the most important file in the src/main/resources/static directory is index.html. The browser loads this page to run your application and it contains everything needed to bootstrap it.

Let’s inspect some parts of it. You will find a <base href='/'> tag which is needed by Angular to make the routing component work in the default mode. Note that you can remove it if you don’t make use of the Router (we will see Routing details later) or if you use the router with the hash strategy on.

Then you will see a bunch of several <link> and <script> tag to load bootstrap.css (this can be removed) and javascript files. Those provide the Angular runtime which is called by your Java/GWT application.

As we talk about it, the javascript file generated from your Java code is imported by this line :

<script src="angular2gwt/angular2gwt.nocache.js"></script>

This script bootstraps GWT’s core and call your application entry point which is the onModuleLoad method of the Application class (which in turn bootstraps Angular with your Java component classes).

The last remarkable thing in this file is this line :

<my-app class="container">Application is loading...</my-app>

This tag is rendered as a <div> until all scripts are loaded. During this period, the “Application is loading” message is displayed. Once the application is initialized, the Angular engine runs and replaces the <my-app> content by the one of the ApplicationComponent.

We will see that just after the Application class.

This class is the entrypoint of your application, meaning that its onModuleLoad method will be the first to be called and it will be called just after the GWT runtime has been initialized.

Angular2Boot entrypoint classes are very simple, the only thing you find is the Angular bootstrapping call :

  .bootstrapModule( ApplicationModule_AngularModule.getNgModulePrototype() );

The bootstrapModule method corresponds to the bootstrapModule function of Angular 2’s PlatformBrowserDynamic module. In fact it is bound to Java through GWT’s JsInterop, so behind the scene it is the same function that is called. The parameter of the bootstrapModule is the result of a call to the ApplicationModule_AngularModule.getNgModulePrototype() method. This method returns an Angular2-compatible constructor of the ApplicationModule class. The ApplicationModule_AngularModule class is automatically generated for you by Angular2Boot, as you will see later on.

So here we just say to Angular to start with the ApplicationModule as the root module of our application.

Just one word on the commented line of code that shows :

/** You can uncomment that line to switch Angular to Production mode */
// Core.enableProdMode();

By default, until this line is uncommented Angular will work in debug mode : it will produce helper messages in the console and also add more runtime data associated with the components of the application (helping tools like Augury to work). If you deploy your application, don’t forget to uncomment this line !

NgModules first appeared in the rc5 version of Angular2. They allow you to split your application into big functional blocks and reuse them in other applications. They allow the Angular tool to perform more optimizations for you : the modules are statically analyzed by the Angular Ahead of Time Compiler (ngc) and some pruning can happen.

Naturally, your java application too should declare a module. This is done in the ApplicationModule class. It reads :

	imports = {
		FormsModule.class },
	declarations = ApplicationComponent.class,
	bootstrap = ApplicationComponent.class )
public class ApplicationModule

It defines the root module of our application. It imports the Angular BrowserModule and FormsModule. The first one brings everything that is needed to make Angular 2 work in the browser (as you may know, Angular can run in other environments than browsers) and the second one (FromsModule) brings useful usual form directives like ngModel. The module then declares the ApplicationComponent component so that it is avalaible to other modules if needed. The bootstrap parameter says that when the module is bootstrapped, it starts with the ApplicationComponent component, which we will examine right now.

Here is the source code of the main component application :

	selector = "my-app",
	template = "<h1>{ {title}}</h1>" +
  	"You can edit the title by changing the text in this box :<br/>"+
  	"<input [(ngModel)]='title'/>" )
public class ApplicationComponent
	private String title = "Your application is working !";

It doesn’t do much but it already uses some of the main concepts of Angular : Components. Here are the very necessary two steps to create an Angular component out of a Java class :

  • add the @Component annotation. This generates metadata about your component for Angular. Refer to the Angular documentation about the meaning of this annotation fields. Putting this annotation triggers the generation of the ApplicationComponent_AngularComponent java class.
  • add the @JsType annotation. This tells the GWT compiler to make this class accessible to the Javascript world. This is required in order that Angular can access your Java classes.

Here with selector = "my-app" we set this class to handle the <my-app> html tag. As you will have guessed, the content generated with this component will replace the content inside the <my-app> tag in the index.html page.

The content generated by the component is defined in the template field in the annotation (template = "<h1>{ { title } }</h1> ..."). It uses the double-brace syntax to refer to the title attribute’s value.

The title field is declared like this:

private String title = "Your application is working !";

The @JsProperty tells the GWT compiler to make the field accesible to the javascript world and to Angular, even thou it is declared private. If it was declared public you would not need to put this annotation (the @JsType annotation on the class itself makes all the public fields and methods accesible to javascript).

If this field’s value change, Angular will know about and the DOM will be updated accordingly (given the change is made inside the angular zone, meaning inside an event handler and so on).

As you can note, the component’s template includes another part : <input [(ngModel)]='title'/>. This creates an input tag whose value is data-bound to the titleattribute of the component object. The ngModel is an angular directive that comes from the FormsModule that is imported in our ApplicationModule. We will dig a bit deeper into this subject later on.

That’s all for the front side of the application for the moment. Now let’s inspect a backend class providing a very basic REST service.

This class contains two parts : one is the REST controller and the other is the main method, called by Spring Boot :

public class ApplicationController
	@RequestMapping( "/test" )
	String test()
		return "This is a test";

	public static void main( String[] args ) throws Exception
	{ ApplicationController.class, args );

Tour of Heroes tutorial

This tutorial walks you through the basics of creating an Angular2Boot application. It is strongly advised to read so that you gain the basic knowledge.

The tutorial is based on the official Angular 2 typescript version of the tutorial. As you will see, the Java and Typescript versions are very similar. It means that you will be able to learn new things on Angular2Boot by reading the Typescript documentation !

Using with another backend technology

While Spring Boot provides a very good platform to host your angular application, you may want to use Angular2Boot with another backend like JBoss, Tomcat, Spark or Jetty.

This is completely possible and documentation and archetypes will be provided soon.

It is even possible to use Angular2Boot only for the front-end and get on with a non-Java technology on the server…


Angular 2 has been wrapped around Typescript and Dart because they allow elegant metadata specification through annotations. Java also has annotations and is a language of choice when it comes to build robust applications.

Angular 2 is a very good framework to build industry grade web applications. It is based on several years of experience with Angular 1 and is now mature and answers most of the developper needs.

GWT provides (optimized) translation from Java to Javascript and bindings to Angular 2. With the latest GWT version (2.8), the new JsInterop specification allows easy interoperability with Javascript. And the SuperDevMode has been improved so that recompile time is greatly reduced, providing a development experience similar to what a Javascript developper can expect.

Add the simplicity of Spring Boot for server side application development and you get Angular2Boot !

IDE Configuration


You need to install m2e-apt component. Otherwise, everything should work out of the box by importing the maven project.


Documentation not yet written

Version matrix

Angular version angular2-gwt.archetype versions angular2-gwt versions
2.0.0 1.6, 1.7-SNAPSHOT 1.6, 1.7-SNAPSHOT
2.0.0 rc 6 1.4, 1.5-SNAPSHOT 1.3, 1.4-SNAPSHOT
2.0.0 rc 5 1.3, 1.4-SNAPSHOT 1.2, 1.3-SNAPSHOT
2.0.0 beta 17 1.1, 1.2-SNAPSHOT 1.0, 1.1-SNAPSHOT
2.0.0 beta 16 1.0 1.0


Sometimes, after changing a lot of code, the GWT SuperDevMode gets confused and does not manage to update anymore. This is a limitation caused by GWT. One way to circumvent this is to clear the project and build it again, but it’s time consumming. Another way of doing so it to quit the GWT SuperDevMode and to run the rm -rf target/gwt-unitCache/ command. This will clear GWT compilation cache. You can then restart the GWT SuperDevMode (mvn gwt:run-codeserver) and things should work fine again.


If you have any question or remark, feel free to use the comment zone at the bottom of the page or to email us directly to

License: MIT license

Useful links

Angular 2 voor schaalbare applicaties

Angular 2 is nog maar net 3 maanden geleden gereleased en wordt al volop ingezet bij VX Company. Met ons ‘YIP’ team hebben we afgelopen zomer een applicatie ontwikkeld voor het project NOTS (een registratiesysteem om 1.1 miljoen huishoudens in Rwanda te voorzien van zonnepanelen) op basis van Java. De front-end van de applicatie is grotendeels gebaseerd op Javascript en dat zorgde soms voor veel technische diepgang die je als programmeur eigenlijk wilt vermijden. Na een geslaagde oplevering van de applicatie kregen we het verzoek om de front-end te herontwikkelen in Angular 2.  Al gauw bleek dat Angular 2 een uitstekend framework was wat niet alleen de complexiteit drastisch verlaagde maar ook de schaalbaarheid van de applicatie ten goede kwam.




Angular 2 is een front-end framework op basis van Javascript en ondersteunt zowel Ecmascript 5,  6 als typescript. Alhoewel de browsers de Ecma 6 standaard nog niet ondersteunen hoef je daar als programmeur geen rekening mee te houden, alle code wordt terug gecompileerd met de ‘Traceur compiler‘ naar browser compatibel Javascript waardoor het in elke browser probleemloos kan renderen. Door typescript is het een stuk makkelijker om de applicatie object georiënteerd te kunnen schrijven, wat in plain Javascript nog best een karwei is waar de scope een belangrijke factor speelt. Angular 2 biedt naast deze voordelen nog meer, de structuur is gebaseerd op componenten die zelf weer componenten kunnen bevatten, de componenten hebben geen weet van elkaar tenzij je er een verbinding tussen legt door inputs en outputs of middels een service. Elk component bestaat uit een klasse die een view template heeft, aangevuld met metadata, die direct verbonden staat met de klasse zelf. Modulair bouwen is dus een stuk eenvoudiger geworden.

De onderstaande user-template laat zien dat de complexiteit laag is en goed leesbaar is, attributen zijn injecteerbaar in de klasse/template en de observables in de klassen zijn van buiten af te vangen.

<div class="row" [hidden]="userEditView || userAddView">
    (availableUsers)="users = $event"
    (userSearchView)="userSearchView = $event"
    (userAddView)="userAddView = $event">

    (userEditView)="userEditView = $event"
    (editUser)="currentUser = $event"
    (selectUser)="selectedUser = $event">

<div class="row" *ngIf="currentUser">
    (userEditView)="userEditView = $event"
    (editedUser)="currentUser = $event"

<div class="row">
    (userAddView)="userAddView = $event"
    (userSearchView)="userSearchView = $event"

Angular 2 kan ook een flinke prestatiewinst opleveren ten opzichte van zijn voorganger Angular. Zodra de applicatie wordt geopend is het voor Angular 2 niet noodzakelijk om de volledige source te downloaden  voordat de applicatie gebruikt kan worden. Zodra de benodigde source is gedownload zal de applicatie direct werken, de rest van de source die nodig is voor geneste secties van de applicatie kan worden binnen gehaald als die sectie ook daadwerkelijk gerenderd moet worden, deze techniek is ook wel bekend als lazy loading. Een grote applicatie hoeft op deze manier dus niet perse trager te zijn wat de gebruikservaring ten goede komt.

Wil je meer te weten te komen over dit onderwerp? Neem gerust contact op met een de onze Angular 2 ontwikkelaars van VX Company.

How to Change JVM Heap Setting (-Xms -Xmx) of Tomcat – Configure file – Run

Apache Tomcat is widely used Web Container in the world. Very big companies run on Apache Tomcat now a days. There are quite a few other alternatives like IBM WebSphere, Geronimo, IIS, etc. but Tomcat is my favorite one too.

It’s very critical for us to configure all correct parameters while running your application in Production environment or even in development env.

In this tutorial we will go over steps on how to configure -Xms, -Xmx and -XX:PermSize value for Tomcat server. Let’s first understand few terms.


Specifies the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 64MB. The upper limit for this value will be approximately 4000m on Solaris 7 and Solaris 8 SPARC platforms and 2000m on Solaris 2.6 and x86 platforms, minus overhead amounts. So, in simple words, you are saying Java to use Maximum of 1024 MB from available memory.

NOTE: there is NO SPACE between -Xmx and 1024m


It’s a size of the heap for the young generation.


It’s used to set size for Permanent Generation. It is where class files are kept.

Another must read: Change -Xmx value of Tomcat in Eclipse IDE

Let’s get started:

Below are the simple steps to change -Xmx / -Xms values or other JVM parameters if you are running Tomcat from command prompt.


Download Apache Tomcat.


Go to Apache Tomcat /bin directory.

Create file for Tomcat Xmx and Xmn value - Crunchify Tips


By default you wont see (for Linux/Mac) or setenv.bat (for windows) file under /bindirectory. You have to create one with below parameters.


  1. Go to command prompt.
  2. Go to <Tomcat Directory>/bin directory
  3. Execute command: ./ run

Run Apache Tomcat using run command - Crunchify


Monitor logfile and you should see your Tomcat started with all your specified parameters in setenv.shfile.

Apache Tomcat Log with Xmx and Xmn value - Crunchify Tips

PS: For Windows environment you need to create setenv.bat file and run Tomcat withcatalina.bat

Subscribe to our newsletter and never miss a post!

Get early access to new articles, plugins, discount codes and brief updates about what’s new with Crunchify! Join more than 21000 subscribers…

Avatar for App Shah

About App Shah

Hello & Good Day from greater New York. I’m an Engineer & founder of Crunchify, the largest free blogging & technical resource site for beginners. Love SEO, SaaS, #webperf, WordPress, Java. With more than 14 millions pageviews / month, Crunchify LLC, has changed the life of over thousands of individual around the globe teaching Java & Web technology without spending a money online. Get latest update on and .

Dependency Injection

Wat is dependency injection?

Stel dat je meerdere componenten, klassen en directives zijn die allemaal een sercive willen gebruiken, dan kan een instantie van de sevice geinjecteerd worden in de klasse of directive. Dat gaat door een instantie van de service in de constructor mee te geven van de klasse of directive.  Je moet Angular aangeven hoe de instantie wordt aangemaakt.

constructor(argument: Service) {}

Providing Dependencies

Het is in Angular mogelijk om in de verschillende klassen elk een eigen instantie van de service te geven. Soms wil je juist dat elke klasse een gedeelde instantie gebruikt van de service, bijvoorbeeld een data service die voor elke klasse hetzelfde gedrag vertoont en dat elke klasse de data naar hetzelfde object schrijft en leest, in dit geval is het dus ongewenst dat elke klasse een eigen instantie krijgt van die service.

Het delen van een instantie kan in Angular op twee manieren, één methode is om de service in een component te plaatsen die hoog in de hiearchie staat, het hoogste component is de app.component.ts. Alle child componenten erven de instantie van de service over. In de parrent klasse moet je de service providen.

provide: [Service]

De tweede methode is bijna hetzelfde. Je kunt de service in het hoogst mogelijke component meegeven door de service in de bootstrap methode mee te geven.

bootstrap(AppComponent, [Service])


Error Handling in the Reactive Extensions

One of the most difficult tasks in asynchronous programming is dealing with errors. Unlike interactive style programming, we cannot simply use the try/catch/finally approach that we use when dealing with blocking code.

try {
  for (var obj in objs) {
} catch (e) {
} finally {

These actions mirror exactly our Observer class which has the following contract for handing zero to infinite items with onNext and optionally handling either an Errorwith onError or successful completion with onCompleted.

interface Observer<T> {
  onNext(value: T) : void
  onError(error: Error) : void
  onCompleted() : void

But the try/catch/finally approach won’t work with asynchronous code. Instead, we have a myriad of ways of handling errors as they occur, and ensure proper disposal of resources.

For example, we might want to do the following:

  • swallow the error and switch over to a backup Observable to continue the sequence
  • swallow the error and emit a default item
  • swallow the error and immediately try to restart the failed Observable
  • swallow the error and try to restart the failed Observable after some back-off interval

We’ll cover each of those scenarios and more in this section.

Catching Errors

The first topic is catching errors as they happen with our streams. In the Reactive Extensions, any error is propogated through the onError channel which halts the sequence. We can compensate for this by using the catch operator, at both the class and instance level.

Using the class level catch method, we can catch errors as they happen with the current sequence and then move to the next sequence should there be an error. For example, we could try getting data from several URLs, it doesn’t matter which since they all have the same data, and then if that fails, default to a cached version, so an error should never propagate. One thing to note is that if get('url') calls succeed, then it will not move onto the next sequence in the list.

var source = Rx.Observable.catch(

var subscription = source.subscribe(
  data => {
    // Display the data as it comes in

We also have an instance version of catch which can be used two ways. The first way is much like the example above, where we can take an existing stream, catch the error and move onto the next stream or Promise.

var source = get('url1').catch(getCachedVersion());

var subscription = source.subscribe(
  data => {
    // Display the data as it comes in

The other overload of catch allows us to inspect the error as it comes in so we can decide which route to take. For example, if an error status code of 500 comes back from our web server, we can assume it is down and then use a cached version.

var source = get('url1').catch(e => {
  if (e.status === 500) {
    return cachedVersion();
  } else {
    return get('url2');

var subscription = source.subscribe(
  data => {
    // Display the data as it comes in

This isn’t the only way to handle errors as there are plenty of others as you’ll see below.

Ignoring Errors with onErrorResumeNext

The Reactive Extensions borrowed from a number of languages in our design. One of those features is bringing On Error Resume Next from Microsoft Visual Basic. This operation specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point. There are some instances with stream processing that you simply want to skip a stream which produces an error and move to the next stream. We can achieve this with a class based and instance based onErrorResumeNext method.

The class based onErrorResumeNext continues a stream that is terminated normally or by an Error with the next stream or Promise. Unlike catch,onErrorResumeNext will continue to the next sequence regardless of whether the previous was in error or not. To make this more concrete, let’s use a simple example of mixing error sequences with normal sequences.

var source = Rx.Observable.onErrorResumeNext(
  Rx.Observable.throw(new Error()),
  Rx.Observable.throw(new Error()),

var subscription = source.subscribe(
  data => console.log(data)
// => 42
// => 56
// => 78

The instance based onErrorResumeNext is similar to the class based version, the only difference being that it is attached to the prototype, but can take another sequence or Promise and continue.

Retrying Sequences

When catching errors isn’t enough and we want to retry our logic, we can do so with retry or retryWhen operators. With the retry operator, we can try a certain operation a number of times before an error is thrown. This is useful when you need to get data from a resource which may have intermittent failures due to load or any other issue.

Let’s take a look at a simple example of trying to get some data from a URL and giving up after three tries.

// Try three times to get the data and then give up
var source = get('url').retry(3);

var subscription = source.subscribe(
  data => console.log(data),
  err => console.log(err)

In the above example, it will give up after three tries and thus call onError if it continues to fail after the third try. We can remedy that by adding catch to use an alternate source.

// Try three times to get the data and then return cached data if still fails
var source = get('url').retry(3).catch(cachedVersion());

var subscription = source.subscribe(
  data => {
    // Displays the data from the URL or cached data

The above case retries immediately upon failure. But what if you want to control when a retry happens? We have the retryWhen operator which allows us to deeply control when the next try happens. We incrementally back off trying again by using the following method:

var source = get('url').retryWhen(
   attempts =>
      .zip(Observable.range(1, 3), (_, i) => i)
      .flatMap(i => {
        console.log('delay retry by ' + i + ' second(s)');
        return Rx.Observable.timer(i * 1000);

var subscription = source.subscribe(
  data => {
    // Displays the data from the URL or cached data
// => delay retry by 1 second(s)
// => delay retry by 2 second(s)
// => Data

Ensuring Cleanup with Finally

We’ve already covered the try/catch part of try/catch/finally, so what about finally? We have the finally operator which calls a function after the source sequence terminates gracefully or exceptionally. This is useful if you are using external resources or need to free up a particular variable upon completion.

In this example, we can ensure that our WebSocket will indeed be closed once the last message is processed.

var socket = new WebSocket('ws://someurl', 'xmpp');

var source = Rx.Observable.from(data)
  .finally(() => socket.close());

var subscription = source.subscribe(
  data => {

But we can do a better job in terms of managing resources if need be by using the using method.

Ensuring Resource Disposal

As stated above, finally can be used to ensure proper cleanup of any resources or perform any side effects as necessary. There is a cleaner approach we can take by creating a disposable wrapper around our object with a dispose method so that when our scope is complete, then the resource is automatically disposed through theusing operator.

function DisposableWebSocket(url, protocol) {
  var socket = new WebSocket(url, protocol);

  // Create a way to close the WebSocket upon completion
  var d = Rx.Disposable.create(() => socket.close());

  d.socket = socket;

  return d;

var source = Rx.Observable.using(
  () => new DisposableWebSocket('ws://someurl', 'xmpp'),
  d => 
      .tap(data => d.socket.send(data));

var subscription = source.subscribe();

Delaying Errors with mergeDelayError

Another issue may arise when you are dealing with flattening sequences into a single sequence and there may be errors along the way. We want a way to flatten without being interrupted by one of our sources being in error. This is much like the other operator mergeAll but the main difference is, instead of immediately bubbling up the error, it holds off until the very end.

To illustrate, we can create this little sample that has an errored sequence in the middle when it is trying to flatten the sequences.

var source1 = Rx.Observable.of(1,2,3);
var source2 = Rx.Observable.throwError(new Error('woops'));
var source3 = Rx.Observable.of(4,5,6);

var source = Rx.Observable.mergeDelayError(source1, source2, source3);

var subscription = source.subscribe(
  x => console.log('onNext: %s', x),
  e => console.log('onError: %s', e),
  () => console.log('onCompleted'));

// => 1
// => 2
// => 3
// => 4
// => 5
// => 6
// => Error: Error: woops

Lazy Loading a Module

Another advantage of using modules to group related pieces of functionality of our application is the ability to load those pieces on demand. Lazy loading modules helps us decrease the startup time. With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes.

To show this relationship, let’s start by defining a simple module that will act as the root module of our example application.


import { NgModule } from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { EagerComponent } from './eager.component';
import { routing } from './app.routing';

  imports: [
  declarations: [
  bootstrap: [AppComponent]
export class AppModule {}

So far this is a very common module that relies on the BrowserModule, has a routing mechanism and two components: AppComponent and EagerComponent. For now, let’s focus on the root component of our application (AppComponent) where the navigation is defined.


import { Component } from '@angular/core';

  selector: 'my-app',
  template: `
    <h1>My App</h1>
      <a routerLink="eager">Eager</a>
      <a routerLink="lazy">Lazy</a>
export class AppComponent {}

Our navigation system has only two paths: eager and lazy. To know what those paths are loading when clicking on them we need to take a look at the routing object that we passed to the root module.


import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { EagerComponent } from './eager.component';

const routes: Routes = [
  { path: '', redirectTo: 'eager', pathMatch: 'full' },
  { path: 'eager', component: EagerComponent },
  { path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

Here we can see that the default path in our application is called eager which will load EagerComponent.


import { Component } from '@angular/core';

  template: '<p>Eager Component</p>'
export class EagerComponent {}

But more importantly, we can see that whenever we try to go to the path lazy, we are going to lazy load a module conveniently called LazyModule. Look closely at the definition of that route:

{ path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }

There’s a few important things to notice here:

  1. We use the property loadChildren instead of component.
  2. We pass a string instead of a symbol to avoid loading the module eagerly.
  3. We define not only the path to the module but the name of the class as well.

There’s nothing special about LazyModule other than it has its own routing and a component calledLazyComponent.


import { NgModule } from '@angular/core';

import { LazyComponent }   from './lazy.component';
import { routing } from './lazy.routing';

  imports: [routing],
  declarations: [LazyComponent]
export class LazyModule {}

If we define the class LazyModule as the default export of the file, we don’t need to define the class name in the loadChildren property as shown above.

The routing object is very simple and only defines the default component to load when navigating to thelazy path.


import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { LazyComponent } from './lazy.component';

const routes: Routes = [
  { path: '', component: LazyComponent }

export const routing: ModuleWithProviders = RouterModule.forChild(routes);

Notice that we use the method call forChild instead of forRoot to create the routing object. We should always do that when creating a routing object for a feature module, no matter if the module is supposed to be eagerly or lazily loaded.

Finally, our LazyComponent is very similar to EagerComponent and is just a placeholder for some text.


import { Component } from '@angular/core';

  template: '<p>Lazy Component</p>'
export class LazyComponent {}

View Example

When we load our application for the first time, the AppModule along the AppComponent will be loaded in the browser and we should see the navigation system and the text “Eager Component”. Until this point, the LazyModule has not being downloaded, only when we click the link “Lazy” the needed code will be downloaded and we will see the message “Lazy Component” in the browser.

We have effectively lazily loaded a module.

Lazy Loading and the Dependency Injection Tree

Lazy loaded modules create their own branch on the Dependency Injection (DI) tree. This means that it’s possible to have services that belong to a lazy loaded module, that are not accessible by the root module or any other eagerly loaded module of our application.

To show this behaviour, let’s continue with the example of the previous section and add aCounterService to our LazyModule.


import { CounterService } from './counter.service';

  providers: [CounterService]
export class LazyModule {}

Here we added the CounterService to the providers array. Our CounterService is a simple class that holds a reference to a counter property.


import { Injectable } from '@angular/core';

export class CounterService {
  counter = 0;

We can modify the LazyComponent to use this service with a button to increment the counter property.


import { Component } from '@angular/core';

import { CounterService } from './counter.service';

  template: `
    <p>Lazy Component</p>
    <button (click)="increaseCounter()">Increase Counter</button>
    <p>Counter: {{ counterService.counter }}</p>
export class LazyComponent {

  constructor(public counterService: CounterService) {}

  increaseCounter() {
    this.counterService.counter += 1;

View Example

The service is working. If we increment the counter and then navigate back and forth between the eagerand the lazy routes, the counter value will persist in the lazy loaded module.

But the question is, how can we verify that the service is isolated and cannot be used in a component that belongs to a different module? Let’s try to use the same service in the EagerComponent.


import { Component } from '@angular/core';
import { CounterService } from './lazy/counter.service';

  template: `
    <p>Eager Component</p>
    <button (click)="increaseCounter()">Increase Counter</button>
    <p>Counter: {{ counterService.counter }}</p>
export class EagerComponent {
  constructor(public counterService: CounterService) {}

  increaseCounter() {
    this.counterService.counter += 1;

If we try to run this new version of our code, we are going to get an error message in the browser console:

No provider for CounterService!

What this error tells us is that the AppModule, where the EagerComponent is defined, has no knowledge of a service called CounterService. CounterService lives in a different branch of the DI tree created forLazyModule when it was lazy loaded in the browser.