报错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
相关产品推荐
相关产品推荐

