Ho un problema quando uso typeScript
con angular2
.
Voglio creare un file helper.ts
esporta molte classi/funzioni comuni da riutilizzare.
Ma il Helper class
ha bisogno di importare altri servizi nel costruttore, in modo che quando un'altra classe importa Helper class
, deve impostare param è quei servizi. Non voglio questo.Come scrivere la classe Helper in dattiloscritto?
Come posso scrivere Helper class
, che posso usare dovunque quando import {Helper} from ..
Questo è il mio campione: 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();
}
}
Per favore aiutatemi, grazie.
Gaurav Mukherjee, grazie – Sophia
è possibile rendere statica la classe helper, quindi non è necessario aggiungere l'helper come proprietà e possiamo invece fare qualcosa come Helper.whatever()? –
@DanHastings È possibile utilizzare la funzione per questo oppure creare un oggetto con valori e funzioni. per esempio. 'const Helper = {qualunque cosa: (a) => {a + 1}}' –