Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

399
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda