从确认对话框中的回调调用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
) { }

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

我在各种组件中放入了一些控制台语句,我想我明白了为什么只有当名称"http";使用。我认为这与范围和/或结束问题有关。。。

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

经验教训。。。

最新更新