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