首页 > 解决方案 > 在确认对话框中从回调调用 HTTP 服务时出错

问题描述

我正在开发一个 Angular (v7) 应用程序,在尝试从对话框组件调用 HTTP 服务时遇到一个奇怪的错误。

与其试图解释我的代码安排,让我只向您展示重要的部分

我的HttpService:

export class HttpService {
   constructor(
      private _http: HttpClient
   ) { }

sendPost = (url, msg = {}, defTimeout = 30000, defRetries = 0) => {

  return this._http
     .post(url, msg, {
        headers: this.getHeaders(),
        observe: "response"
     })
 ...

使用我的 Http 服务的应用服务:

export class CompanyProfileService {
   constructor(
      private httpService: HttpService,
      private env: EnvironmentService
   ) { }

   public setMyCompanyProfile$(msg: UpdateMessage) {
      let url = this.env.setCompanyProfileURL;
      let retVal = this.httpService.sendPost(url, msg)
      return retVal;
   }

当我直接从我的组件调用它们时,上述方法方案完美地工作。也就是说,我将特定于应用程序的服务注入到我的组件中,并且可以很好地调用这些方法。

但是,我们有一些用例,在我们进行更新之前,我们希望用户确认他们的操作。为此,我们创建了(使用角度材质对话框)一个通用的包装器/库来放置一个对话框,然后如果用户选择“OK”,对话框完成调用服务 http 方法。此对话框的部分数据是要调用的服务函数的名称(例如 setMyCompanyProfile$)和要在请求中发送的消息。

我们早期的一些服务使用上述方案工作,但突然之间,我们开始在控制台中收到运行时错误,如下所示:

ERROR TypeError: Cannot read property 'sendPost' of undefined
at ConfirmComponent.push../src/app/services/company-profile.service.ts.CompanyProfileService.setMyCompanyProfile$ [as serviceFcn] (company-profile.service.ts:65)
at ConfirmComponent.push../src/app/services/confirm/confirm.component.ts.ConfirmComponent.onProceed (confirm.component.ts:50)
at Object.handleEvent (confirm.component.html:3)
at handleEvent (core.js:23107)
at callWithDebugContext (core.js:24177)
at Object.debugHandleEvent [as handleEvent] (core.js:23904)
at dispatchEvent (core.js:20556)
at core.js:21003
at HTMLButtonElement.<anonymous> (platform-browser.js:993)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)

在仔细比较了上述通过对话框调用时不起作用的情况与通过对话框调用时起作用的情况,我发现唯一的区别是我为注入的 HttpService 提供的变量的名称。当我使用 httpService 时,找不到 sendPost 方法。当我使用http时,可以找到sendPost方法。

构造函数上的此签名有效:

export class CompanyProfileService {
       constructor(
          private http: HttpService,
          private env: EnvironmentService
       ) { }**

构造函数上的此签名导致错误:

export class CompanyProfileService {
   constructor(
      private httpService: HttpService,
      private env: EnvironmentService
   ) { }

为什么私有变量的名称很重要?

标签: angularcallbackdialoghttpclienttypeerror

解决方案


我在我的各种组件中放置了一些控制台语句,我想我明白了为什么它只在使用名称“http”时才有效。我认为这与范围和/或关闭问题有关......

我应该以不同的方式设计它并使用继承......

学过的知识...


推荐阅读