Sophia Sophia - 21 days ago 15
TypeScript Question

How to write Helper class in typescript?

I have a problem when use

typeScript
with
angular2
.

I want create one
helper.ts
file exports many classed/functions common to re-use.

But
Helper class
need import others service in constructor, so that when another class import
Helper class
, It have to set param is those service. I don't want this.

How I can write
Helper class
, that I can use anywhere when
import {Helper} from ..


This is my sample:
Helper.ts

import {TranslateService, TranslatePipe} from 'ng2-translate/ng2-translate';
import {Inject, Component} from 'angular2/core';


@Component({
providers: [TranslateService]
})

export class Helpper {
public trans;
public lang;
public properties;

constructor(trans: TranslateService) {
this.trans = trans;
//This is variable for translate function
this.lang = this.trans.currentLang;
this.properties = this.trans.translations[this.lang];
}

translate(key) {
return this.properties[key];
}
}


RenderTab.ts

import {Component, Inject, Injectable} from 'angular2/core';
import {Helper} from './helpper'

@Component({
providers: [Helper]
})

export class RenderTab {
public helper;

constructor(helper: Helper) {
this.helper = helper;
}

render() {
var test = this.helper.translate('string');
}
}


HomePage.ts

import {Component, Inject, Injectable} from 'angular2/core';
import {RenderTab} from './RenderTab'

@Component({
selector: 'div',
templateUrl: './HomePage.html',
providers: [RenderTab]
})

export class ColorPicker {
public renderTab;

constructor(renderTab: RenderTab) {
this.renderTab = renderTab;

var test = this.renderTab.render();
}
}


Please help me, thanks.

Answer

First of all class Helper should be a service, which should be injectable.

import {Injectable} from "angular2/core";
import {Http} from "angular2/http";
import {TranslateService} from 'ng2-translate/ng2-translate';

@Injectable()
export class Helper {
   constructor(private http: Http, private translateService: TranslateService) {

   }

}

Now you can simply inject this helper and use it in any component you like.

import {Helper} from "./helper.ts";
@Component({
   providers: [Helper],
...
})
export class MyComponent{
   constructor(public helper: Helper) {}
}
Comments