如何在打字稿中写Helper类?

前端之家收集整理的这篇文章主要介绍了如何在打字稿中写Helper类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用带有angular2的typeScript时遇到问题.
我想创建一个helper.ts文件导出许多常用的类或函数重用.
但是Helper类需要在构造函数中导入其他服务,这样当另一个类导入Helper类时,它必须设置param才是那些服务.我不想要这个.

我如何编写Helper类,我可以在导入{Helper}时从任何地方使用..

这是我的样本:
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,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();
    }
}

请帮帮我,谢谢.

首先,类Helper应该是一个服务,应该是可注射的.
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {TranslateService} from "ng2-translate";

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

   }

}

现在您可以简单地注入此帮助程序并在您喜欢的任何组件中使用它.

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

更新:您需要在根模块的providers数组中添加服务才能使其正常工作

猜你在找的Angularjs相关文章