【问题标题】:How to use 'This' inside an Ajax call in angular [duplicate]如何在 Angular 的 Ajax 调用中使用“This”[重复]
【发布时间】: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(...))

标签: ajax angular this


【解决方案1】:

试试这个。

saveCart(data: any): void { 
/* Other code */
var that = this;
$.ajax({ 
    url: environment.domain + '/cart', 
    type:       "POST", 
    headers: config, 
    data: body, 
    contentType: "application/json",
    dataType: "json", 
    async: false,
    success:function(response){
    //The 'this' below is undefined **********
     that.profileService.logout().subscribe(result => { console.log('User was logged out', result) })
    }
 })

【讨论】:

  • 不起作用。已经尝试过“那个”
  • 您是否尝试过成功回调而不是完成?请检查更新的答案。这可能是语法错误,因为我已通过移动设备对其进行了更新。因此,以防万一语法错误,请相应地解决它。 ?
  • 也尝试过成功。没有任何区别。
  • 能否请您创建一个要点或小提琴并分享它,以便我可以测试它。
  • 这通常适用于所有人。所以离我的终点只有一点。
【解决方案2】:

尝试使用这种方式。

选项 1

在Ajax调用之前,设置一个新变量...

var that = this;

现在您可以使用 that 代替这个。它将与此相同。

选项 2

您可以尝试使用ES6 语法。我没有尝试过 Ajax,但我经常在我的代码中使用它,它对我来说很好用。

$.ajax({ 
url: environment.domain + '/cart', 
type:       "POST", 
headers: config, 
data: body, 
contentType: "application/json",
dataType: "json", 
async: false,
success:(() =>{  <----------------Hear is the change
    this...
}) =>{   
}
})

【讨论】:

  • 我分享了相同的解决方案。但对于提出问题的人来说,它不起作用。个人认为是不可能的。可能是错误在其他地方。你有什么想法?
  • 是的,第一个解决方案是相同的,但我也提供了另一种选择。我每天都在我的代码中使用它。
  • 我认为这可能是代码中的一些小问题。我希望它可以工作。但不要担心我们俩的答案都是正确的。 :) 编码愉快。
  • 哟让我们看看会发生什么。 ?
  • @JavaQuest 你的问题有什么更新吗?
猜你喜欢
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多