使用从其自身组件上的可观察对象检索的数据的方法 returns undefined when used as Input()

method that uses data retrieved from an observable on its own component returns undefined when used as Input()

我创建了一个模板 example.component.html,它接收一个方法作为其点击操作的变量:

<div>
  <button (click)="method()">click here</button>
</div>

example.component.ts 文件中,该方法来自 input(),因此我可以在多种情况下使用此模板:

@Component({
  selector: 'example',
  templateUrl: './example.component.html',
})
    export class ExampleComponent implements OnInit {
      @Input() method;
    
      constructor() {}
    
      ngOnInit(): void {}
    }

这就是事情变得复杂的地方。在父组件中,单击时将触发的方法使用来自可观察对象的变量:

parent-example.component.html

  <example [method]="onClick"></example>

parent-example.component.ts

@Component({
  selector: 'parent-example',
  templateUrl: './parent-example.component.html',
})
export class ParentExampleComponent implements OnInit {
  @Input() method;
  business;

  constructor(businessEntityService: BusinessEntityService) {
    businessEntityService.entities$.subscribe(
      data => (this.business = data),
    );
  }

  onClick() {
    console.log(this.business);
  }

  ngOnInit(): void {}
}

即使父组件正在订阅 businessEntityService observable 并且我已经检查它实际上有数据,但当我单击按钮时,控制台会记录 undefined.

我知道这可能与作用域有关,并且堆栈正在子组件中寻找 this.business,但是我很想知道是否有调用使用订阅变量的方法的方法从它自己的组件作为 Input().

this 上下文正在丢失(我认为)。将 class 方法作为参数

传递时可能发生

ParentExampleComponent#onClick 方法替换为:

onClick = () => {
    console.log(this.business);
}

注意: 在幕后,Typescript 现在会将 onClick 视为 class 属性,并将该代码移至构造函数中.使用箭头函数锁定该函数的 this 上下文