DarkW1nter
DarkW1nter

Reputation: 2851

Angular 6 - trying to pass a function to a function in another class

I have a table where I click a button on a row to update a bool field on the row. I then want to refresh the table. What I have below is:

SaveItem - sets the value I want update, then passes the object, id and a function to the function doing the call.

editItem - makes the call and updates the item, but I then want it to then run the function passed in, which is the last function below, getItems, which would re-populate the object the table is based on.

It fails on the last line of editItem with

TypeError: getItems is not a function

Can anyone tell me what I'm doing wrong?

SaveItem(flag: boolean) {
    this.item$.Published = flag;
    this.edit.editItem(this.item$, this.id, this.getItems(this.items$));
  }


editItem(item, id, getItems) {
    const url = this.apiUrl + '/tables/Items/' + id
    this.http.patch(url, item, httpOptions).subscribe((data) => getItems(data));
  }


getItems(itemList: Item[]): void{
  this.data.getItems()
  .subscribe(data => this.items$ = data);
}

Upvotes: 0

Views: 82

Answers (1)

Juan M. Medina
Juan M. Medina

Reputation: 638

You must declare the callback as a flat function, not the result of the function. See this little tidbit, which you can run on the Typescript Scratchpad by clicking here. I did put a couple comments like "// THIS IS THE IMPORTANT CHANGE" where this applies.

class Item {
    Published: boolean
}

class Observable {
    subscribe(callback: (data: Array<Item>) => any) {
        callback(new Array<Item>());
    }
}

class Test {

    apiUrl: string;
    http = {
        patch: (url, item, httpOptions) => { 
            return new Observable();
        }
    };
    item$ = new Item();
    items$: Item[];
    id: 'someid';
    edit = {
        editItem: (item: any, id: string, callback: (data: Item[]) => void) => {
            // THIS IS THE IMPORTANT CHANGE
            return this.editItem(item, id, callback);
        }
    }
    data = {
        getItems: () => { 
            return new Observable();
        }
    };

    editItem(item, id, getItems) {
        const httpOptions: any = {};
        const url = this.apiUrl + '/tables/Items/' + id
        this.http.patch(url, item, httpOptions).subscribe((data) => this.getItems(data));
    }

    getItems(itemList: Item[]): void {
        this.data.getItems()
            .subscribe(data => { this.items$ = data; alert("Hey! I got called"); });
    }

    SaveItem(flag: boolean) {
        this.item$.Published = flag;
        // THIS IS THE IMPORTANT CHANGE
        this.edit.editItem(this.item$, this.id, this.getItems);
    }
}

let test = new Test();
test.SaveItem(true);

Upvotes: 1

Related Questions