You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用服务方法报错:getTaxByCategory未定义,求修正

解决Angular中Cannot read property 'getTaxByCategory' of undefined的问题

嘿,我来帮你搞定这个报错!你遇到的ERROR TypeError: Cannot read property 'getTaxByCategory' of undefined,本质是调用this.taxService时它是undefined,通常是服务未正确注入或者事件处理器的this上下文绑定错误导致的,咱们一步步来修复:

一、先确认服务已正确注入

首先要确保你的组件能拿到TaxService实例:

  1. 组件构造函数注入服务
    在你的组件类里添加构造函数,注入TaxService:
constructor(private taxService: TaxService) { }
  1. 确保服务已被Angular识别
    如果你的服务是全局可用的,服务类上应该有根级注入的装饰器:
@Injectable({
  providedIn: 'root'
})
export class TaxService {
  // ... 你的服务代码
}

如果不是全局提供,需要在组件所在模块的providers数组里添加TaxService。

二、修复事件处理器的this上下文问题

你在HTML里直接绑定onValueChanged: categoryChanged时,函数的this会指向dxSelectBox的编辑器实例,而不是你的组件实例,所以组件里的this.taxService就找不到了。这里有三种解决方法:

方法一:用箭头函数定义事件处理器

把组件里的categoryChanged改成箭头函数,这样this会始终绑定到组件实例:

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

方法二:在HTML中用bind绑定this

修改HTML里的onValueChanged配置,同时顺手把showClearButton的字符串'true'改成布尔值true:

<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.bind(this) }">
</dxi-item>

方法三:在组件初始化时绑定上下文

在组件的ngOnInit里初始化editorOptions,手动绑定this:

editorOptions: any;
category: any[]; // 假设这是你的分类数据集合

ngOnInit(): void {
  this.editorOptions = {
    items: this.category,
    placeholder: 'Select Category ',
    displayExpr: 'categoryName',
    valueExpr: 'id',
    showClearButton: true,
    onValueChanged: this.categoryChanged.bind(this)
  };
}

// 原来的事件处理器保持不变
categoryChanged(event: any){ 
  this.categoryId = event.value; 
  this.taxService.getTaxByCategory(this.categoryId).subscribe(result => { 
    console.log(result); 
  }) 
}

然后HTML简化成:

<dxi-item [label]="{ text: ' Category ' }" dataField="categoryId" alignment="right" editorType="dxSelectBox" [editorOptions]="editorOptions">
</dxi-item>

三、可选优化:服务代码简化

你的服务方法里return this.taxes = ...可以简化,不需要把Observable赋值给this.taxes(除非你在服务里需要复用这个实例),直接返回即可:

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

内容的提问来源于stack exchange,提问作者Random

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:09:10