Brian Vander Plaats



17 Oct 2016

Converting JSON Types

In a post last year, I found a simple csv to JSON technique that worked well - but today I noticed a significant limitation - all numbers were converted to strings, which isn’t very useful for setting up mock data for TypeScript.

I created the simple node.js file below to convert an existing JSON file (using the technique above), by specifying one or more values to convert in the file. It’s not especially robust, but it works for my current needs. A few comments:

  • input file must be utf-8
  • null values converted to string type get set to blank values.
  • strings of "null" are converted to null for int or float types.
  • you may specify any number of inputs fields.
  • Only supports simple file structures, no nested arrays inside the JSON objects.


11 Oct 2016

Angular2 Testing Introduction

Looking at unit testing in Angular2, following the offical docs. Unit Testing is a large topic, so this is just an initial look and summary of what I’ve learned so far.

Why Unit Testing

According to the documentation, Unit Testing as three main purposes:

  1. Guard against regressions in code. Changing code in an established application is frequently a source of bugs, and having a battery of tests available can alert the developer to issues quickly (assuming there is a test that covers that particular issue)
  2. Describe how services, pipes, and components should operate. Even if you are good at reading code, it is not always easy to visualize what inputs and outputs should look like.
  3. Expose design flaws in component design. If it is hard to write a test for a component, it is a strong sign that the component has design flaws, such as doing too many things, containing unnecessary dependencies, etc.


Jasmine is a unit testing framework for JavaScript that the Angular team recommends using.

  • In Jasmine, a test is known as a “spec”.
  • Specs are stored in a .spec.ts file. Each component/service/pipe that has tests should have their own spec file, e.g. App.component.spec.ts.
  • specs are defined with the global Jasmine function it()
  • Multiple specs for the same component are known as a “suite”. A suite is defined with the global jasmine function describe()
  • The purpose of a spec is to define an assertion about what a component should do, or be. An assertion is either true or false. for example, an assertion may be: When we pass 2 to the function square(), the result will be 4
  • To create an assertion in Jasmine, use the expect() global function, inside an it() function.
  • Jasmine defines a large number of “Matchers” to be used with expect()
    • toBe()
    • toEqual()
    • toBeUndefined()
    • toBeTruthy()
    • toContain()
    • etc.

Example Test

describe('Math Tests', () => {
    it('Math.pow(2,32) should be 4294967296', () => {

    it ('Math.sqrt(64) should be 8', () => {


Jasmine tests need to be run to see if they succeed or fail. Karma is a unit test runner the Angular team recommends. Karma runs via the node command: npm test. It launches a browser instance that hosts the tests, and can be configured to run all tests automatically after application code is updated.

After each test run, the results will output in a command window (not the browser). While a bit verbose, you will be able to clearly see if any tests have failed.

I’m not using karma for the demo code below, but it is a part of the angular-cli environment

Jasmine + Angular

By itself, Jasmine knows nothing about an Angular application, so we need to use an Angular test infrastructure to make useful unit tests.

  • Need to import all components/services that the test/spec(s) will be using
  • use the global Jasmine function beforeEach() to initialize components. beforeEach() runs before every individual it() execution.
  • some items such as pipes and services do not depend on the angular environment running, and can be tested with little setup in Jasmine, besides instantiating the class.
  • the primary class for interacting with the Angular environment is the TestBed class. This class is responsible for:
    • Instantiating the component that will be tested via TestBed.createComponent(). this will return a special ComponentFixture class that contains the component instance as well as a few other testing properties
    • configuring the angular environment via TestBed.configureTestingModule()
    • querying the components template + rendered DOM via debugElement and nativeElement properties of the ComponentFixture. Note that these elements are hierarchical i.e. debugElement can contain one or more child debugElements
    • provide access to the component’s properties & methods via fixture.componentInstance. Note that the properties will not be defined until fixture.detectChanges() is run.

Example Component Test

import { TestBed, ComponentFixture } from '@angular/core/testing';
import { By }           from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import {SampleComponent } from './sample.component';

let comp:    SampleComponent;
let fixture: ComponentFixture<SampleComponnent>;

describe('SampleComponent', () => { 
  beforeEach(() => {
      declarations: [ SampleComponent ], 

    fixture = TestBed.createComponent(SampleComponent);
    comp = fixture.componentInstance;
  it ('Should create the component', () => {
    let app = fixture.debugElement.componentInstance; 
  it ('H1 title should be: Sample Component', () => {
    let de = fixture.debugElement.query(By.css('h1'));
    expect(de.nativeElement.textContent).toEqual("Sample Component");
  it ('component property should be 25', () => {
    fixture.detectChanges(); // the component does not initialize until detect changes happens
  it ('component component property should be undefined before initialization', () => {


04 Oct 2016

An Initial Look at RxJS Observables

A major change in Angular2 from Angular1 is a transition from using promises to observables in the implementation of the new Http angular module. You can listen to angular team member Rob Wormald discuss this change in an April 2016 talk.

Observables are part of ReactiveX. This is a major cross-platform set of libraries designed to work with several languages. The version Angular uses is called RxJS, also known as Reactive Extensions for JavasScript.

Angular 1 $http.get() using Promises

  method: 'GET',
  url: ''
}).then(function successCallback(response) {
   //do stuff

Angular 2 http.get() using Observables

Observable<string[]> observable =  this.http.get('')
                  .map(res: Response => res.json() as string[]);

var observer = observable.subscribe(function(data){
    //do stuff

Both Promises and Observables are mechanisms for responding to asynchronous events. Promises are designed to retrieve data exactly once. Once the .then() fires, we’re done. Observables are different. They have the ability to send data multiple times. Notice in the above example we “subscribe” to the observable. This is the equivalent of the .then() handler in a promise. However, the observable can call this handler multiple times!

Here’s an example of how this works:

First, we create an Observable

var source = Rx.Observable.create(function(observer){
    var itemsToEmit = 5;
    var itemsEmitted = 0;
    while (itemsEmitted < itemsToEmit){
        observer.onNext(Math.floor(Math.random() * (101-1) + 1));
        itemsEmitted += 1;

The observable is where the async operations happen. At some point, the Observable needs to pass along some information to the observer. This is done with the .onNext() function. Notice that this is called multiple times. When this happens we say that we are emitting data to the observer. It’s the observer’s job to decide what to do with this data, which is handled in the subscription:

        document.getElementById('subscriptionOneOutput').innerHTML += emittedValue + ', ';

Each time .onNext() is called, the function(emittedValue) handler is called. The observer defines three event handlers for .onNext(), onError(), and onCompleted(). We can pass these inline to a .subscribe(), or create the observer directly:

Rx.Observer.create (function(emittedValue){
        document.getElementById('subscriptionTwoOutput').innerHTML += emittedValue + ', ';
    }, // onNext()
    {}, // onError()
        document.getElementById('subscriptionTwoOutput').innerHTML += '... done!';
    }); // onCompleted()


The .onError() and .onCompleted() both pass information to the observer, but once they fire the Observable does not emit any more data. The observer does not need to define handlers for these events.

You can try this out in this fiddle:

Observables can be created automatically from many sources:

  • Rx.Observable.from() - from an array or collection
  • Rx.Observable.fromEvent(<target control>, <event name>) - from a DOM event
  • Rx.Observable.fromPromise() - even from promises

Additionally, Observables define methods for manipulating the data returned to the observer:

  • .map( x=> 10 * x) - transform data. this is very useful for parsing HTTP response to get the data payload
  • .filter(x => x > 2) - limit data returned

A good place to start reviewing Observables is in this online book, but be warned, this is a very deep topic. You don’t need to understand all of this to use Observables in Angular, but understanding Observables outside the context of Angular will enable you to use them more effectively.

30 Sep 2016

Angular InMemoryDataService

Reviewing the HTTP Angular Tutorial this morning, I was really confused how the sample “Web API” was working in the sample plunker.

It started out as:

search(term: string): Observable<Hero[]> {
    return this.http
               .map((r: Response) => r.json().data as Hero[]);

app/heroes/?name=${term} is clearly the API call, but where is the function that processes it? I assumed that this was in HeroesComponent, since app.routing.ts defines the heroes route.

    path: 'heroes',
    component: HeroesComponent

But why would the API be in a component class, that makes no sense! Moreover, the only likely function,

  getHeroes(): void {
        .then(heroes => this.heroes = heroes);

doesn’t include any parameters, and a console.log() very clearly showed this function is not called during search operations.

I was close to just assuming there was some invisible api I couldn’t see, when I re-read the tutorial and noticed something about the InMemoryDataService:

import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    let heroes = [
      {id: 11, name: 'Mr. Nice'},
      {id: 12, name: 'Narco'},
      {id: 13, name: 'Bombasto'},
      {id: 14, name: 'Celeritas'},
      {id: 15, name: 'Magneta'},
      {id: 16, name: 'RubberMan'},
      {id: 17, name: 'Dynama'},
      {id: 18, name: 'Dr IQ'},
      {id: 19, name: 'Magma'},
      {id: 20, name: 'Tornado'}
    return {heroes};

the return name is {heroes}. What if I changed that to {heroesx}? Sure enough, the app/heroes call failed. I then tried changing the service url in hero.service.ts to

  private heroesUrl = 'app/heroesx'; 

And the service worked again. That’s pretty interesting behavior, but certainly not intuitive…

The next question was how the name filter worked


As I didn’t see any functions for that. Well it turns out this is also a feature of the InMemoryDataService. You can pass a filter for any property of the json, so this will work as well:


28 Sep 2016

Angular2 Simple Edit Page

Going over the Angular2 docs on forms, and decided to bring forward my 1.x simple forms demo

It ports over fairly well, but a significant number of changes needed to be made. Honestly it seems like it would take an enormous effort to convert an existing 1.x application to Angular2.

Specific Changes

  • update directives
    • ng-model -> [(ngModel)]
    • ng-class -> [ngClass]
    • ng-submit -> (ngSubmit)
    • ng-show -> [hidden] (could have also used *ngIf)
    • ng-maxlength -> [maxlength]
    • ng-disabled -> [disabled]
  • instead of defining a telephone filter, I created a pipe
  • Create ManufacturerService with a type class and a mock
  • Create generic LookupService for the list of states
  • angular.copy() does not have a direct replacement in Angular2. Object.assign() works well as long as a deep copy is not needed, which isn’t the case here (Manufacturer doesn’t contain collections, just simple types)
  • instead of defining an empty manufacturer JSON object, we can instantiate a new, empty manufacturer. (to be used when the new button is clicked)
  • The currency filter will not work with an empty string. In edit mode, blanking out the <input> causes <span class="displayValue" [ngClass]="pageMode">{{manufacturer.creditLimit | currency }}</span> to raise an exception. The workaround is to set the <input type="number"
    • alternately, one could argue that the view controls should not be bound to the same object the edit controls are bound to
  • I wasn’t able to access the manufacturerForm properly from the simple-edit-form.component.ts.
    • within the template, manufacturerForm.valid is available, but in the component.ts it is undefined
    • ended up using manufacturerForm.checkValidity()
    • this plunker (not mine) shows the forms valid property as accessible in component.ts, but I didn’t get this to work
  • needed to set #manufacturerForm="ngForm" inside the <form>
  • In addition to the id, name attributes, needed to set #nameInput="ngModel" inside the <input>’s using validation.
  • spent a lot of time figuring out why nameInput.errors.required was giving undefined errors. It looks like you always need to check for valid first, as the errors collection is only defined when errors are present: [hidden]="nameInput.valid || !nameInput.errors.required" The || causes a short-circuit evaluation in the expression. If you remove the nameInput.valid from the example below you can repro this issue.