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.

5
  • this.$onInit instead of $ngInit, should work. Not sure angular 1 is already a little bit back for me but try it. this.$onInit = function () { your code }; Commented Jul 5, 2017 at 7:18
  • Ah, it was a typo in example, ofc $onInit. Thx Commented Jul 5, 2017 at 7:19
  • Still it throws "this is undefinded" ? Commented Jul 5, 2017 at 7:22
  • Yup, it does... Commented Jul 5, 2017 at 7:24
  • 1
    stackoverflow.com/questions/20627138/… Commented Jul 5, 2017 at 7:26

1 Answer 1

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.