【发布时间】:2019-10-26 18:32:53
【问题描述】:
一旦我得到 Ajax 调用的响应,我就会尝试使用“this”。 但“这个”似乎是未定义的。我发现很少有使用“绑定”的文章,但我不确定如何实现绑定。
在 ajax 调用中使用“this”没有任何问题。我按预期从后端得到响应。
saveCart(data: any): void {
let body: any = {}
body.data = data
body = JSON.stringify(body)
// the 'this' works here as expected.
let config = this.config.getHeaders() as any
$.ajax({
url: environment.domain + '/cart',
type: "POST",
headers: config,
data: body,
contentType: "application/json",
dataType: "json",
async: false
}).done(function (response) {
// The 'this' below is undefined **********
this.profileService.logout().subscribe(result => {
console.log('User was logged out', result)
})
})
}
更新:有几个人质疑我为什么不使用 httpClient。
当用户关闭浏览器时调用此函数。使用 angular angular 的 httpclient 会在关闭前将浏览器(繁重的后端代码)冻结几秒钟。所以选择了ajax调用。
下面是我在其他地方使用 angular httpClient 的代码
this.http.post(environment.domain + url, body, options)
.pipe(retryWhen(this.config.handleRetry))
.pipe(catchError(this.config.handleError))
【问题讨论】:
-
如果是 Angular,那你为什么使用 jQuery 来进行 HTTP 调用,而不是 Angular 自己的 HttpClient?
-
你能补充一下你是如何使用httpClient的吗?这将是比 jQuery 的 Ajax 更好的方法
-
仅对于这种特殊情况,我必须使用 Ajax 调用。其他任何地方都在使用 httpClient。他们都按预期工作。
-
使用箭头函数语法,您将可以访问它。
-
另外,技术上,你只需要调用
.pipe一次,你可以给retryWhen和catchError等多个操作符作为参数:.pipe(retryWhen(...), catchError(...))