-1

I am trying to use 'this' once I get response from Ajax call. but 'this' seems to be undefined. I found few articles using the 'bind', but I am not sure how to implement the bind.

I don't have any problem using 'this' inside the ajax call. I get response from backend as expected.

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)
      })  
    })
  }

Update: Couple of folks had question about why I am not using httpClient.

This function is called when the user closes the browser. Using angular angular's httpclient is freezing the browser (heavy backend code) for few seconds before it closes. so opted for ajax call.

below is the code I am using everywhere else using angular httpClient

  this.http.post(environment.domain + url, body, options)
      .pipe(retryWhen(this.config.handleRetry))
      .pipe(catchError(this.config.handleError))
JavaQuest
  • 671
  • 6
  • 23
  • If it's Angular, then for what reason are you using jQuery to make HTTP calls, instead of Angular's own HttpClient? – mbojko Oct 26 '19 at 18:39
  • Can you add how you are using the httpClient? It will be a better approach than the jQuery's Ajax – yazantahhan Oct 26 '19 at 18:44
  • Only for this particular case I have to use Ajax call. else everywhere httpClient is being used. All of them are working as expected. – JavaQuest Oct 26 '19 at 18:51
  • 2
    Use arrow function syntax and you will have access to this. – Elias Soares Oct 26 '19 at 18:52
  • 1
    Also, a technicality, you need to call `.pipe` only once, and you can give multiple operators like retryWhen and catchError as parameters: `.pipe(retryWhen(...), catchError(...))` – Robin De Schepper Oct 26 '19 at 19:10

2 Answers2

2

Try this one.

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) })
    }
 })
Milind Patel
  • 2,677
  • 4
  • 14
  • 31
1

Try to use this way.

Option 1

Before Ajax call, set a new variable...

var that = this;

Now you can user that instead of this. It will work same as this.

Option 2

You can try with ES6 syntax. I haven't try with Ajax but I used this in my code regularly and it works fine for me.

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