0

I've created some simple class by this example https://www.typescriptlang.org/docs/handbook/classes.html with private and public methods, but I've got an error: ERROR TypeError: Cannot read property 'somePrivateMethod' of undefined.

import { Injectable } from '@angular/core';

@Injectable()
export class MyService {
  constructor() {}

  somePublicMethod() {
    this.somePrivateMethod();
  }

  private somePrivateMethod() {
    return true;
  }
}

I just call myService.somePublicMethod from my component and do not use somePrivateMethod.

I call it in my component like these:

   constructor(
      private myService: MyService
    ) { }

    ngOnInit() {
      inputs.map(this.myService.somePublicMethod)
    }

I tired to solve it like this:

   constructor(
      private myService: MyService
    ) { }

    ngOnInit() {
      const myMethod = this.myService.somePublicMethod.bind(this)
      inputs.map(myMethod)
    }

But anyway I've got the same error. Where is the problem?

rel1x
  • 2,351
  • 4
  • 34
  • 62
  • Is this the only place you are calling the method, or is it being used some where else also? – Venomy Nov 10 '17 at 08:50
  • @Venomy I've updated my post. Yes, it's the only place where I use my private method – rel1x Nov 10 '17 at 09:07
  • What happens if, in your component, you just call `this.myService.somePublicMethod()` instead of the `inputs.map...`? – Venomy Nov 10 '17 at 09:14
  • @Venomy oops, now it works – rel1x Nov 10 '17 at 09:17
  • Glad to hear that! :D – Venomy Nov 10 '17 at 09:18
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Estus Flask Nov 10 '17 at 09:18
  • @Venomy anyway can't understand how to solve it. I've tried `this.myService.somePublicMethod.bind(this)` but it throws the same error – rel1x Nov 10 '17 at 09:36
  • What are you trying to achieve with `inputs.map` ? – Venomy Nov 10 '17 at 09:37
  • @Venomy apply this.myService.somePublicMethod on each element of `inputs` – rel1x Nov 10 '17 at 09:37
  • 1
    `inputs.map(this.myService.somePublicMethod.bind(this.myService))`, or simpler: `inputs.map(input => this.myService.somePublicMethod(input))`. This will create an array of undefined, though, since the method doesn't return anything. – JB Nizet Nov 10 '17 at 09:39
  • @JBNizet thanks a lot! – rel1x Nov 10 '17 at 09:42

0 Answers0