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

报错TypeError: this.contactService.verifyContact(...).subscribe不是函数求解决

问题排查与解决:subscribe不是函数错误

问题根源

contactService.verifyContact方法返回的是Promise(MongoDB的findOne本身返回Promise,外层的.then也会保留Promise类型),而subscribe是RxJS Observable专属的方法,对Promise调用subscribe自然会触发TypeError。

解决方案

方案1:改用Promise的then/catch处理逻辑

直接用Promise的链式调用替代Observable的subscribe:

createEmergencyContactBoat(emergencyContactBoat: EmergencyContactBoat, number: string) {
    return this.db.connect().then(connection => {
        return this.contactService.verifyContact(number, connection)
            .then((result: any) => {
                if (!result){
                    throw new Error(ErrorMessage.CONTACT_DONT_EXIST);
                } 
                emergencyContactBoat.emergencyContact = result.id;
                return connection.collection(this.collection).insertOne(emergencyContactBoat);
            });
    });
}

方案2:用async/await简化异步逻辑(推荐)

将方法改为async函数,用await处理所有异步操作,代码可读性更高:

async createEmergencyContactBoat(emergencyContactBoat: EmergencyContactBoat, number: string) {
    const connection = await this.db.connect();
    const result = await this.contactService.verifyContact(number, connection);
    
    if (!result) {
        throw new Error(ErrorMessage.CONTACT_DONT_EXIST);
    }
    
    emergencyContactBoat.emergencyContact = result.id;
    return connection.collection(this.collection).insertOne(emergencyContactBoat);
}

额外优化:简化verifyContact方法

原方法里的.then是冗余的,直接返回findOne的Promise即可:

verifyContact(number: string, connection: any ) {
    return connection.collection(this.collection).findOne({
        emergencyContact: {$eq: true}, 
        contact: {$eq: number}
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:36:11