简体   繁体   中英

Accessing base member from derived class in function

I have created Angular2 + Typescript project. 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

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.

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. Inside callback this binding is bound to something else and you loose the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM