【问题标题】:Call function in event handler事件处理程序中的调用函数
【发布时间】:2019-04-29 18:27:11
【问题描述】:

我正在从事件处理程序中获取一个 ID,现在我想使用此 ID 调用我的服务方法,但我收到方法未定义错误。请纠正我,因为我是 Angular 的新手。 错误类型错误:无法读取未定义的属性“getTaxByCategory”

component.ts

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

服务方式

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>

【问题讨论】:

  • 你在哪里得到错误?
  • @ritaj 无法读取未定义的属性“getTaxByCategory”。
  • @AqibHafeez 显示所有与taxService相关的TS相关代码
  • @AqibHafeez 在您声明/注入taxService的位置显示TS代码
  • @AqibHafeez 并且请不要在评论部分添加相关代码。

标签: angular typescript


【解决方案1】:

问题是当传递onValueChanged: categoryChanged 时,categoryChanged 有自己对this 的引用(this 不再是组件)。将categoryChanged 更改为箭头函数以使其工作。

箭头函数在进一步传递时保留this 的引用。

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

你可以在this SO question找到更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多