[英]Accessing base member from derived class in function
I have created Angular2 + Typescript project. 我已经创建了Angular2 + Typescript项目。 I have there alot of tables so I want to have something like base component for that.
我有很多表,所以我想拥有一些像基本组件这样的东西。
There is my base component: 有我的基本组成部分:
export abstract class ManagementComponent<T> implements BaseComponent {
protected selectedItem: T;
protected items: Array<T>;
}
Now there is my child component. 现在有我的孩子部分。 I would like to get all items from http and then assign it into base class
我想从http获取所有项目,然后将其分配给基类
export class CompetencesComponent extends ManagementComponent<Competence> implements OnInit {
thisField: string;
constructor(private service: CompetencesService) {
super();
}
ngOnInit(): void {
this.getCompetences();
}
private getCompetences() {
this.service.getCompetences().subscribe(function (competences: Array<Competence>) {
this.thisField // ok
this.items // not ok
})
}
}
Any idea how I can access base fields from subscribe methods? 知道如何从订阅方法访问基本字段吗?
Currently I'd expect that you wouldn't be able to reference either thisField
or items
, because you should be losing the this
context inside your subscription function. 目前,我希望您无法引用
thisField
或items
,因为您应该在订阅函数中丢失this
上下文。
You can switch to an arrow function to retain context: 您可以切换到箭头功能以保留上下文:
this.service.getCompetences().subscribe((competences: Array<Competence>) => { ... }
You can set list of competencies to parent class as follow: 您可以如下设置父类的能力列表:
private getCompetences() {
var self = this;
this.service.getCompetences().subscribe(function (competences: Array<Competence>) {
this.thisField // ok
self.items = competences; // not ok
})
}
The reason you are unable to access items
property through this
binding is the scope. 您无法通过
this
绑定访问items
属性的原因是范围。 Inside callback this
binding is bound to something else and you loose the context. 在回调内部,
this
绑定绑定到其他对象,并且您松开了上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.