Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

401
Vistas
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.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Helper classes should only contain static functions or variable, if not they are not different from services. Please Correct me if I'm mistaken.

One of ways to create Helper class without Injectable or adding it to providers is posted here Thanks to k7sleeper

Copying the code from the mentioned post for quick reference.

utils.ts :

export default class Utils {
    static doSomething(val: string) { return val; }
    static doSomethingElse(val: string) { return val; }
}

Usage:

import Utils from './utils'
export class MyClass {
    constructor()
    {
        Utils.doSomething("test");
    }
}

But reading more about this, it makes sense to inject them through Injectable and providers, but I would still have all the methods as static and the class without constructor

over 4 years ago · Santiago Trujillo Denunciar

0

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

import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {TranslateService} from "ng2-translate";

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

   }

}

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

import {HelperService} from "./helper.service.ts";
@Component({
   ...
})
export class MyComponent{
   constructor(public helperService: HelperService) {}
}

Update: You need to add the service in providers array of the root module for it to work, or for angular6+, the service can be provided as follows

@Injectable({
  providedIn: 'root'
})
export class HelperService {
   ...
}
over 4 years ago · Santiago Trujillo Denunciar

0

Your Helper class corresponds to a service and since you want to inject another service in you need add the @Injectable decorator (not the @Component one):

Import {Injectable} from 'angular2/core';

@Injectable()
export class Helper {
  (...)
}

Since it's part of dependency injection, all parameters of its constructor will be provided by Angular2 itself. You don't need to provide them by your own and instantiate yourself this class to be able it. Simply inject it where you want to use it...

You need then to the corresponding provider at when bootstrapping your application:

bootstrap(AppComponent, [ Helper ]);

Or at a component level but can only be used within processing triggered by the component.

@Component({
  (...)
  providers: [ Helper ]
})
export class SomeComponent {
  (...)
}

For more details about dependency injection and hierarchical injectors, you could have a look at this question:

  • No provider for ObservableDataService
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda