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

Angular服务HTTP依赖注入无返回结果排查求助

问题排查请求

我在辅助函数中调用MachineLearningService服务,该服务接收参数并从API返回响应。但在给辅助函数构造函数添加HttpClient依赖后,控制台无输出也无响应;移除该依赖则可返回模拟数据,希望得到问题排查思路。

辅助函数代码

@Injectable()
export class JsExpressionHelper {
  // constructor() {}
  constructor(private http: HttpClient) { }

  evaluateML(...args) {
    const htsDataSource = new MachineLearningService(this.http);
    console.log("---here", htsDataSource.getHTSRiskScore(args))

    //return htsDataSource.getHTSRiskScore(args);
    return htsDataSource.getHTSRiskScore(args).subscribe(resp => {return resp})
  }

  get helperFunctions() {
    const helper = this;
    return {
      evaluateML: helper.evaluateML
    };
  }
}

服务代码

@Injectable()
export class MachineLearningService {
  constructor(private http: HttpClient) { }

  public getHTSRiskScore(params) {
    let predictionVariables = {
      AgeAtTest: params.age,
      MonthsSinceLastTest: params.monthsSinceLastTestInt > 0 ? params.monthsSinceLastTestInt : 0,
      GenderMale: params.gender == 'M' ? 1 : 0,
      GenderFemale: params.gender == 'F' ? 1 : 0,
      KeyPopulationTypeGP: 0,
      KeyPopulationTypeSW: 0
    };

    const headers = { 'content-type': 'application/json' }
    const url = 'http://1.1.1.1:8600/openmrs/ws/rest/v1/keml/casefindingscore';
    return this.http.post(`${url}`, predictionVariables, { 'headers': headers });
  }
}

排查思路

  • 检查HttpClientModule导入:确保根模块(如AppModule)中已经导入HttpClientModule,Angular使用HttpClient必须先导入该模块,未导入会导致注入失败且无明确报错。
  • 规范服务实例化方式:不要手动用new MachineLearningService(this.http)创建服务实例,应该将MachineLearningService注入到JsExpressionHelper中。修改构造函数为:
    constructor(private http: HttpClient, private mlService: MachineLearningService) { }
    
    然后在evaluateML中直接调用this.mlService.getHTSRiskScore(args),依赖注入由Angular管理可避免上下文异常。
  • 完善Observable订阅逻辑:当前subscribe(resp => {return resp})无法返回值,且未处理错误。修改订阅代码,添加错误回调以捕获请求异常:
    this.mlService.getHTSRiskScore(args).subscribe(
      resp => {
        console.log('响应数据:', resp);
        // 这里处理返回值逻辑
      },
      err => {
        console.error('请求错误:', err);
      }
    )
    
  • 排查跨域问题:若前端与API不在同一域名下,浏览器会触发CORS拦截,检查控制台是否有跨域报错,需后端配置CORS允许前端域名访问。
  • 验证API地址与参数:确认http://1.1.1.1:8600可正常访问,检查predictionVariables的字段、类型是否符合API要求,避免因参数错误导致请求无响应。
  • 确认服务注册正确:确保JsExpressionHelper和MachineLearningService都在模块的providers数组中注册,或使用@Injectable({ providedIn: 'root' })标记服务,保证依赖注入正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:58:21