TypeScript中私有方法的意外行为

时间:2017-11-10 08:45:34

标签: angular typescript

我已经使用私有和公共方法通过此示例https://www.typescriptlang.org/docs/handbook/classes.html创建了一些简单的类,但我遇到了错误: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;
  }
}

我只是从我的组件中调用myService.somePublicMethod,不要使用somePrivateMethod

我在我的组件中称它为:

   constructor(
      private myService: MyService
    ) { }

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

我厌倦了解决这个问题:

   constructor(
      private myService: MyService
    ) { }

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

但无论如何我有同样的错误。问题在哪里?

0 个答案:

没有答案
相关问题