phil
phil

Reputation: 2187

Data fetch not complete but complete function of subscribe firing

I have an Angular app which is doing:

ngOnInit(): void {
    this._translationsService.getSegments()
        .subscribe(
        tus => this.transUnits = tus,
        error => this.errorMessage = <any>error,
        this.initialize
        );

In initialize() I have

initialize() {
    for (var tu of this.transUnits) {
        // try to iterate over array
    }
}

I keep getting:

Uncaught TypeError: Cannot read property 'length' of undefined
at SafeSubscriber.TranslationEditor.initialize [as _complete] (translation-editor.component.ts:80)

presumably because the data response has not completed.

Should i set some kind of timeout for a few milliseconds?

Upvotes: 0

Views: 44

Answers (1)

paulpdaniels
paulpdaniels

Reputation: 18663

The problem is that Javascript does not preserving the this argument when you are passing through a function reference. You need to either bind this to the call ala this.initialize.bind(this) or you need to call it with an arrow function which does preserve the closing scope.

ngOnInit(): void {
    this._translationsService.getSegments()
        .subscribe(
        tus => this.transUnits = tus,
        error => this.errorMessage = <any>error,
        () => this.initialize
        );

Reference

Upvotes: 1

Related Questions