Angular按钮点击报错TypeError: onSubmitExporter2()不是函数求解决
解决方案
核心问题
模板中调用的onSubmitExporter2()属于DataTransfer类,但当前模板(schedule.component.html)的上下文是ScheduleComponent类,导致找不到该方法,触发TypeError。
方案1:将方法迁移到ScheduleComponent类中
把onSubmitExporter2()方法直接复制到schedule.component.ts的ScheduleComponent类内:
// schedule.component.ts export class ScheduleComponent { constructor(private opsWebDataService: OpsWebDataService) {} // 确保已注入该服务 public onSubmitExporter2(): void { console.log('onSubmitExporter2() called'); const exporter: Exporter = { loading: false, success: false, successMessage: '', error: false, errorMessage: '', info: '', exportTime: '', exportStatus: '', name: 'Download Proba-3 Pass Plan', endpoint: '', description: '', returnFile: false, parameters: [] }; const exporterPath = 'adapter/gsms/exporter/proba3_pass_plan_export'; const queryParams = new Map<string, string>(); queryParams.set('download', 'true'); this.opsWebDataService.exporter(exporterPath, queryParams).subscribe( (r) => { if (!exporter.returnFile) { exporter.info = r.info; exporter.exportTime = r.last_export; exporter.exportStatus = r.status; } else { const disposition = r.headers.get('content-disposition'); let filename = disposition.split(';')[1].trim().split('=')[1]; filename = filename.replace(/"/g, ''); const file = new File([r.body], filename, { type: r.headers.get('content-type') }); saveAs(file); } this.onSuccessExport(exporter); // 确保onSuccessExport也在当前类中,或调整调用方式 }, (error) => { console.error(error); } ); } // 如果onSuccessExport是DataTransfer中的方法,需要迁移或注入DataTransfer后调用 private onSuccessExport(exporter: Exporter): void { // 实现逻辑 } }
方案2:注入DataTransfer服务并调用其方法
如果希望保留方法在DataTransfer类中,需将其声明为可注入服务,再在ScheduleComponent中注入并调用:
- 标记
DataTransfer为服务:
// data-transfer.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' // 或在对应模块中提供 }) export class DataTransfer { constructor(private opsWebDataService: OpsWebDataService) {} public onSubmitExporter2(): void { // 原方法逻辑 } public onSuccessExport(exporter: Exporter): void { // 原方法逻辑 } }
- 在
ScheduleComponent中注入并暴露给模板:
// schedule.component.ts import { DataTransfer } from './path-to/data-transfer.service'; export class ScheduleComponent { constructor(public dataTransfer: DataTransfer) {} // 用public让模板可访问 }
- 修改模板中的点击事件:
<button type="submit" (click)="dataTransfer.onSubmitExporter2()">Propose passes</button>
额外检查项
- 确保
opsWebDataService已正确注入到对应类中 - 若按钮位于
ng-template、嵌套组件内,需确认模板上下文是否指向正确的组件实例 - 检查
onSuccessExport方法的归属,确保调用时上下文正确
内容的提问来源于stack exchange,提问作者Luca Pizzuto
相关产品推荐
相关产品推荐

