Kirschi Kirschi - 1 year ago 101
TypeScript Question

How to call correct this in Angular Service in TypeScript

I have a TypeScript angular project and want to refactor it to use services. My problem is now that I call this in the service but at runtime it is not the service class as expected but the controller class. How can I call functions inside my service from the service itself?

Here are the 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);


constructor($scope: angular.IScope, $http: angular.IHttpService, helperSvc: IHelperService) {
this.Scope.GetModel = helperSvc.GetModel;


<select ng-model="ae.Scope.Model"
ng-options="type.Id as type.Value for type in GetModel('Types')"></select>

Results in

Error: this.getModelEnum is not a function

This worked fine as long as the GetModel/getModelEnum functions were inside the controller.

(What bothered me most was that google always stripped
from my search query. Results were about something completely different then of course...)

Answer Source

In both TypeScript and JavaScript the this reference inside a function is determined on the call site. Calling controller.Scope.GetModel() will bind the this reference to the scope object instead of the helper service.

All you have to do is to is to explicitly bind this:

this.Scope.GetModel = helperSvc.GetModel.bind(helperSvc);
// or
this.Scope.GetModel = (model:string): Array<any> => helperSvc.GetModel(model);

Or use the function bind syntax if you have a compiler that supports it:

this.Scope.GetModel = ::helperSvc.GetModel;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download