This sounds like a duplicate question but I've tried solutions from those questions. I'm still facing the issue. I've a boolean variable in the global space and I'm trying to set the value inside a method which is called after a POST request.
TS
import ...;
@Component({
...
})
export class FileUploadComponent implements OnInit {
constructor(
private http: HttpClient,
...
) {}
ngOnInit(): void {}
hasError: boolean = false; // <----------- this is the variable
public dropped() {
...
this.http
.post(
'http://localhost:8090/.../file-process/upload',
formData,
{ headers: headers, responseType: 'json' }
)
.pipe(catchError(this.handleError)) // <------- control will go here
.subscribe((res: any) => {
console.log('checking', res);
});
});
} else {
...
}
}
}
private handleError(error: HttpErrorResponse) {
this.hasError = true; // <--- Error: ERROR TypeError: Cannot set properties of undefined (setting 'hasError')
}
}
After fixing this line:
.pipe(catchError(this.handleError.bind(this)))
Please pitch in.
CodePudding user response:
This is a problem with the this context in javascript. You need to wrap your function call in a lambda like this:
.pipe(catchError(err => this.handleError(err)))
More specifically the this
object in a function is dependent on how it is called. Arrow functions do have a different behaviour. More details are explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
CodePudding user response:
This shows error because you are directly referring a method from a class which results in changing its context when calling that method.
Instead you can bind that handleError() method with this
context like below.
import ...;
@Component({
...
})
export class FileUploadComponent implements OnInit {
constructor(
private http: HttpClient,
...
) {}
ngOnInit(): void {}
hasError: boolean = false; // <----------- this is the variable
public dropped() {
...
this.http
.post(
'http://localhost:8090/.../file-process/upload',
formData,
{ headers: headers, responseType: 'json' }
)
.pipe(catchError(this.handleError.bind(this))) // <------- control will go here with binded this
.subscribe((res: any) => {
console.log('checking', res);
});
});
} else {
...
}
}
}
private handleError(error: HttpErrorResponse) {
this.hasError = true; // <--- Error: ERROR TypeError: Cannot set properties of undefined (setting 'hasError')
}
}