Random
Random

Reputation: 69

Call function in event handler

I'm getting an ID from event handler now I want to call my service method using this ID but I'm getting method undefined error. please correct me because I am new to Angular. ERROR TypeError: Cannot read property 'getTaxByCategory' of undefined

component.ts

categoryChanged(event: any){
  //console.log(event.previousValue);
  this.categoryId = event.value;
  this.taxService.getTaxByCategory(this.categoryId).subscribe(result => {
    console.log(result);
  })
}

service method

public getTaxByCategory(categoryId: number): Observable < any > {
  return this.taxes = this.apollo.watchQuery<Query["taxGet"]>(
    { query: taxGetByCategory, variables: { categoryId } }
  ).valueChanges.pipe(map(({ data }: { data: any }) => {
    console.log("returned Data");
    return data.taxGet;
  }));
}

HTML

<dxi-item itemType="group">
            <dxi-item   [label]="{ text: '  Category ' }"
            dataField="categoryId"
            alignment="right"
            editorType="dxSelectBox" 
            [editorOptions]="{
                items: category,
                placeholder: 'Select Category ',
                displayExpr: 'categoryName',
                valueExpr: 'id',
                showClearButton: 'true',
                onValueChanged: categoryChanged
                 }">
              </dxi-item>

Upvotes: 1

Views: 1114

Answers (1)

kvetis
kvetis

Reputation: 7351

The problem is when passing the onValueChanged: categoryChanged the categoryChanged has its own reference to this (this is no longer the component). Change the categoryChanged to arrow function to make this work.

Arrow functions preserve the reference of this when they're passed further.

categoryChanged = (event: any) => {
  //console.log(event.previousValue);
  this.categoryId = event.value;
  this.taxService.getTaxByCategory(this.categoryId).subscribe(result => {
    console.log(result);
  })
}

You can find more info about that in this SO question

Upvotes: 3

Related Questions