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

如何修复TypeError: fiatService.findById is not a function错误

问题分析与修复方案

首先,你遇到的TypeError: fiatService.findById is not a function错误,最可能的原因是导入路径错误:你的FiatService导入CurrencyService的路径不正确,导致它继承的不是你定义了findById方法的那个抽象类。

看你的FiatService代码:

import { CurrencyService } from './interface/currency.service';

如果你的CurrencyService实际文件是在service目录下(比如./service/currency.service.ts),而不是interface目录,那这个导入路径就错了,导致FiatService没有继承到findById方法。你需要修正这个导入路径,确保指向正确的CurrencyService文件。


其他代码问题修复

除了路径问题,你的代码还有几个逻辑错误需要修正,否则即使解决了当前报错,后续也会出现问题:

  1. Service基类的upsert方法逻辑错误
    当前的upsert用对象展开运算符处理数组,会把数组转为对象,完全不符合预期。应该改为检查元素是否存在,再更新或添加:
public upsert(m: M): void {
    const currentList = [...this._list.value];
    const existingIndex = currentList.findIndex(item => item.getId() === m.getId());
    if (existingIndex !== -1) {
        currentList[existingIndex] = m; // 更新现有元素
    } else {
        currentList.push(m); // 添加新元素
    }
    this._list.next(currentList);
}
  1. Service基类的addItem方法逻辑错误
    当前addItem会直接替换整个数组为只有新元素的数组,应该添加到现有数组中:
public addItem(m: M): void {
    this._list.next([...this._list.value, m]);
}
  1. Service基类的deleteItem方法修改原数组
    直接用splice修改原数组不符合RxJS的不可变数据原则,应该创建新数组过滤掉要删除的元素:
public deleteItem(m: M): void {
    const newList = this._list.value.filter(item => item !== m);
    this._list.next(newList);
}
  1. Service基类的getItemById方法逻辑错误
    数组不能直接用id作为索引查找元素,应该用find方法:
public getItemById(id: string): M {
    return this.list.find(item => item.getId() === id);
}
  1. CurrencyService的findById方法优化
    不需要在构造函数里绑定this(实例方法调用时this会自动指向实例),并且可以用find简化逻辑:
export abstract class CurrencyService<C extends Currency> extends Service<C> {
    public constructor() {
        super();
        // 移除不必要的this绑定
        // this.findById = this.findById.bind(this);
    }
    public findById(s: string): C {
        return this._list.value.find(item => item.getId() === s);
    }
}

测试代码补充

确保你的Fiat类正确实现了Currency接口,比如:

export class Fiat implements Currency {
    constructor(private id: string, private code: string, private name: string) {}
    getId(): string {
        return this.id;
    }
    // 实现Currency接口的其他方法(如果有的话)
}

修正这些问题后,你的fiatService.findById('1')应该可以正常调用并返回对应的Fiat实例了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:15:43