我创建了一个模板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
上下文正在丢失(我认为)。将类方法作为参数传递时可能会发生
将 ParentExampleComponent#onClick
方法替换为:
onClick = () => {
console.log(this.business);
}
注意:在幕后,Typescript 现在会将 onClick
视为类属性,并将该代码移至构造函数中。使用箭头函数会锁定该函数的 this
上下文
关于angular - 使用从其自己的组件上的可观察对象检索的数据的方法在用作 Input() 时返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70090250/