Angular+Electron中配置Thrift调用API遇引用错误的排查
myService_myAPI_args is not defined错误的解决方案 问题场景
我在Angular应用中调用Thrift API,执行以下命令生成客户端文件:
thrift-0.18.1.exe -r --gen js:ts <myService.thrift>
将生成的js和ts文件复制到项目后,通过pnpm add thrift安装了Thrift依赖,随后编写了调用代码:
import * as thrift from 'thrift'; import { MyServiceClient } from './myService'; import { Injectable } from '@angular/core'; @Injectable() export class TestMyClient { constructor() { const host = 'localhost'; const port = 45000; const opts = { transport: thrift.TBufferedTransport, protocol: thrift.TJSONProtocol, headers: { 'Content-Type': 'application/vnd.apache.thrift.json', }, https: true, path: '/url/path', useCORS: true, }; const connection = thrift.createXHRConnection(host, port, opts); const thriftClient = thrift.createXHRClient(MyServiceClient, connection); connection.on('error', (err) => { console.error(err); }); const data = thriftClient.myAPI(); console.log(`data received: ${data}`); } }
运行时抛出错误:
Uncaught ReferenceError: myService_myAPI_args is not defined
该错误由Webpack打包生成的客户端文件时抛出,请问是否遗漏了必要配置步骤?
解决方案
这个错误是因为Thrift生成的参数类型文件未被正确引入或打包,以下是具体修复步骤:
检查生成文件完整性
执行Thrift生成命令后,除了myService.ts和myService.js,还会生成对应的参数定义文件(如myService_types.ts/myService_types.js),这类文件包含myService_myAPI_args这类参数结构的定义,必须确保它们被完整复制到项目中。手动引入类型文件
在你的TestMyClient服务中,补充导入Thrift生成的类型文件:import './myService_types'; // 根据实际生成的文件名调整路径也可以检查
myService.ts文件,确保它已经自动引入了类型依赖,若没有则手动添加导入语句。调整Angular编译配置
在tsconfig.json的include数组中添加生成文件所在目录,确保Angular CLI能编译到这些文件:"include": [ "src/**/*", "src/thrift-generated/**/*" // 替换为你的Thrift生成文件实际目录 ]若Webpack仍无法识别相关模块,可在
angular.json的build.options.scripts中添加生成的js文件路径,确保它们被提前加载。校验Thrift生成命令参数
确认--gen js:ts参数是否适配当前Thrift版本,部分版本可能需要额外参数确保类型定义与客户端代码关联正确;也可以先尝试去掉:ts参数生成纯JS代码测试,再逐步适配TypeScript环境。修正异步调用逻辑
注意Thrift API调用是异步的,直接赋值会拿到Promise对象,需改用异步方式调用:@Injectable() export class TestMyClient { constructor() { // 原有连接初始化代码... this.callMyAPI(); } async callMyAPI() { try { const data = await thriftClient.myAPI(); console.log(`data received: ${data}`); } catch (err) { console.error(err); } } }
内容的提问来源于stack exchange,提问作者Sachin Parashar

