如何将函数传递给 TypeScript 中的服务

How to pass a function to a service in TypeScript

我在 angular 中有一个调用 webapi 方法的服务:

export class FormulasService extends ServiceBase{
    constructor(){super();}

    renameFormula(id:string, name:string):ng.IPromise<any>{
        var cmd = {id:id, name:name};
        return this.executeCommand('RenameFormula', cmd);
    }
}

现在我有一个在所有模块中都通用的组件,所以它需要一个函数作为参数:

export class RenameModalCtrl extends ControllerBase{
    static $inject=['viewModel']
    constructor(private viewModel:RenameModalModel){
        super();
    }
    saveChanges(){
        this.viewModel.serviceFunction(this.viewModel.id, this.viewModel.name);
    }
}

它的型号:

export class RenameModalModel{
    constructor(
        public model:any, 
        public serviceMethod:(id:string, name:string)=>ng.IPromise<any>)
}

观点:

...
<input class="form-control" ng-model="modal.viewModel.model.name" />
<button type="submit" ng-click="modal.saveChanges()">Save Changes</button>
...

viewModel 在 angular.ui.bootstrap.modal 的解析阶段解析。 我使用 Controler-As 语法,所以视图中的模态是 RenameModalCtrl。

rename()
    {
        var modalInstance = this.$modal.open({
            animation: true,
            controller: 'renameModalCtrl as modal',
            templateUrl: 'renameModal.html',
            resolve: {
                viewModel: new RenameModalModel(this.itemModel, this.formulasService.renameFormula)                    
            }
        });
    }

现在一切正常,除了在服务中。在服务中 'this' 是实际模型,而不是服务。所以它失败了:this.executeCommand('RenameFormula', cmd);

如何解决这个问题? 请帮助

谢谢

您需要使用 => 语法为 class 方法绑定到正确的 "this" 引用,像这样重写 renameFormula:

renameFormula = (id: string, name: string): ng.IPromise<any> => {
    var cmd = { id: id, name: name };
    return this.executeCommand('RenameFormula', cmd);
}

此处有更多详细信息:

https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript