如何解决在确认对话框中从回调调用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;
}
当我直接从组件中调用它们时,上述方法方案可以完美地工作。也就是说,我将特定于应用程序的服务注入到组件中,并且可以很好地调用这些方法。
但是,我们有一些用例,在进行更新之前,我们希望用户确认其操作。为此,我们创建了一个通用包装器/库(使用角度材质对话框),该包装器/库建立了一个对话框,然后,如果用户选择“确定”,则对话框完成将调用服务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”时它才起作用的原因。我认为这与范围和/或关闭问题有关...
我应该对此进行不同的设计并使用继承...
经验教训...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。