0

I have a problem with angular 8 (used in ionic 5). My class has the method initPizzas(). Here the injected pizzaModel is used. initPizzas() is called in ngOnInit() and everything works fine. But when I call delete(), initPizzas() is triggered in the then() function of the prmise returned by the deleteBy() function and I get the error:

Uncaught Error: Uncaught (in promise): TypeError: Cannot read property 'pizzaModel' of undefined TypeError: Cannot read property 'pizzaModel' of undefined

import {Component, OnInit} from '@angular/core';
import {PizzaModel} from './pizza-model';
import {CoreService} from '../core/core.service';
import {IonItemSliding} from '@ionic/angular';

@Component({
    selector: 'app-pizzas',
    templateUrl: './pizzas.page.html',
    styleUrls: ['./pizzas.page.scss'],
})

export class PizzasPage implements OnInit {
    pizzas: any[];

    constructor(private pizzaModel: PizzaModel, private coreService: CoreService) {
    }

    ngOnInit() {
        this.initPizzas();
    }

    initPizzas() {
        // after called in ngOnInit() everything's fine
        // after delete() is called and the promise had been resolved the following "this" is "undefined" :-(

        this.pizzaModel.findAll({
            order: 'date DESC'
        }).then((pizzas) => {
            this.pizzas = pizzas;
        });
    }

    delete(item: IonItemSliding, pizza: PizzaModel) {
        this.pizzaModel.deleteBy().then(this.initPizzas).catch(this.initPizzas);
    }
}


// pizzaModel (simplified for the sake of simplicity)

deleteBy(query: string, values): Promise<any> {
    return new Promise((resolve, reject) => {
        resolve();
    });
}

Any help is highly appreciated. I really don't get it :-(

Thanks in advance!

The_Unknown
  • 988
  • 2
  • 11
  • 22
  • 1
    Try `.then(() => { this.initPizzas(); })`. Or define the callback as an arrow function: `initPizzas = () => { ... }`. – ConnorsFan Apr 11 '20 at 19:04
  • Omg,it works. But why? Where's the difference to my code? – The_Unknown Apr 11 '20 at 19:06
  • 1
    See the duplicate reference, or the section "No separate this" in [this MDN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – ConnorsFan Apr 11 '20 at 19:08
  • Mhm, I don't quite get it still. I understand how () => {} works (making it obsolete to set "this" to a variable to get into a function's scope. But what exactly happens in my case? I pass in a reference to a function and it's called by "resolve()" in the promise. So why exactly is "this" undefined then? – The_Unknown Apr 11 '20 at 19:12
  • I suggest to read the duplicate reference for more detailed explanations. Please note that you could also use `.then(this.initPizzas.bind(this))`. – ConnorsFan Apr 11 '20 at 19:16
  • Ah, I see, it depends from where the function is called. Thanks for pointing me into the right direction! – The_Unknown Apr 11 '20 at 19:28

0 Answers0