1

I have a service written with TypeScript. Something like:

export default class AServiceClass {

    constructor(private $http: ng.IHttpService, ...) {}

    method1(data : any) : void {
        this.$http(...)
    }

    method2(data : any) : void {
        this.$http(...)
    }
}

And I have a controller class, that utilize this service:

export default class AControllerClass {

    constructor(private aService: AServiceClass, ...) {}

    $onInit(){

        let method = true ? this.aService.method1 : this.aService.method2;
        method({ ... data ... });
    }
}

Service methods throw an Exception - this is undefind. If I use it like this.aService.method1({ ... data ... }), all is fine. Ofc I can do method.bind(aService)({ ... data ... }) or method.call(aService, { ... data ... }), but why there is a scope difference?

Thx.

Kindzoku
  • 1,368
  • 1
  • 10
  • 29

1 Answers1

1

Your method1 method is invoked without a context so this inside it will be undefined. You have to call it with the aService object as context or explicitly set the context using call or apply or explicitly bind the context using bind:

this.aService.method1(); // `this` will be aService inside `method1`

method.call(aService, args);

method.apply(aService, [args]);

// Or bind using `bind`:

let method = true ? this.aService.method1.bind(this.aService) : this.aService.method2.bind(this.aService);

method(); 
Saravana
  • 37,852
  • 18
  • 100
  • 108