angularjs - How to call correct this in Angular Service in TypeScript -


i have typescript angular project , want refactor use services. problem call in service @ runtime not service class expected controller class. how can call functions inside service service itself?

here relevant code fragments:

helper service

export interface ihelperservice {     log(msg: string): void;     getmodel(model: string): array<any>; }  export class helperservice implements ihelperservice {     public getmodel(model: string): array<any> {         return this.getmodelenum(model);     }      private getmodelenum(model: string): array<any> {         ...     } }  let module: angular.imodule = angular.module("myapp", ["ngtouch"]); module.service('helpersvc', helperservice); 

controller

constructor($scope: angular.iscope, $http: angular.ihttpservice, helpersvc: ihelperservice) {     this.scope.getmodel = helpersvc.getmodel; } 

html

<select ng-model="ae.scope.model"     ng-options="type.id type.value type in getmodel('types')"></select> 

results in

error: this.getmodelenum not function

this worked fine long getmodel/getmodelenum functions inside controller.

(what bothered me google stripped this search query. results different of course...)

in both typescript , javascript this reference inside function determined on call site. calling controller.scope.getmodel() bind this reference scope object instead of helper service.

all have is explicitly bind this:

this.scope.getmodel = helpersvc.getmodel.bind(helpersvc); // or this.scope.getmodel = (model:string): array<any> => helpersvc.getmodel(model); 

or use function bind syntax if have compiler supports it:

this.scope.getmodel = ::helpersvc.getmodel; 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -