angulartypescripthorizon

Correct way to import Horizon IO into angular 2 project


The way I'm currently importing HorizonIO into my angular 2 project is as follows:

var horizon = require('@horizon/client');

@Injectable()
export class DbService {
    private horizon;

    constructor() {
        this.horizon = Horizon({host: 'localhost:8181'});
    }
}

Now I don't feel that this is the correct way as I should simply be able to

import { Horizon } from '@horizon/client';

Although it doesn't throw an error, the variable isn't usable.

Thought/comments?


Solution

  • The ES6 import equivalent of

    var Horizon = require('@horizon/client');
    

    is

    import * as Horizon from '@horizon/client';
    

    What you did is the equivalent of

    var Horizon = require('@horizon/client').Horizon;
    

    edit:

    I now use the following code to make horizon injectable:

    import { Injectable } from '@angular/core';
    import * as Hz from '@horizon/client';
    
    @Injectable()
    export class Horizon extends Function {
      private _hz;
    
      constructor() {
        super('...args', 'return this._hz(...args)');
        this._hz = new Hz({host: 'localhost:8181'});
    
        return this.bind(this);
      }
    }
    

    It can then be injected and called like you would when directly importing it:

    constructor(hz: Horizon){
      hz('messages').watch().subscribe(...);
    }
    

    Not exactly sure if this has any benefits over importing Horizon directly, but it feels more angularish to use DI.