Currently, I am attempting to retrieve data from an XMLHttpRequest's onreadystatechange
callback. Logging the data works perfectly fine within the callback function. However, when I try to use this data outside of the callback function with this.processedData.next(xttp)
, it generates the following error:
core.js:5828 ERROR TypeError: Cannot read property 'processedData' of undefined
at callbackXttp (output.service.ts:55)
at XMLHttpRequest.xhttp.onreadystatechange [as __zone_symbol__ON_PROPERTYreadystatechange] (output.service.ts:35)
at XMLHttpRequest.wrapFn (zone-evergreen.js:1202)
at ZoneDelegate.invokeTask (zone-evergreen.js:400)
at Object.onInvokeTask (core.js:40744)
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Zone.runTask (zone-evergreen.js:168)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:481)
at invokeTask (zone-evergreen.js:1596)
at XMLHttpRequest.globalZoneAwareCallback (zone-evergreen.js:1622)
The issue might be related to the asynchronous nature of the request. My attempt to address this involved using a callback function.
export class OutputService {
processedData: ReplaySubject<any>;
constructor(private router: Router) {
this.processedData = new ReplaySubject<any>();
}
doCalculation(a, b, z) {
this.request(a, b, z, this.callbackXttp);
}
request(a, b, z, callback) {
const V = {classes: a, absolute: b, z};
const Val = JSON.stringify(V);
let response = 0;
console.log('Request Data: ' + Val);
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
response = JSON.parse(this.responseText);
callback(response);
}
};
xhttp.open('POST', 'http://127.0.0.1:8000/', true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(Val);
}
callbackXttp(xttp) {
const object = [
...
];
this.processedData.next(xttp);
this.router.navigate(['/output']);
}
getProcessedData(): Observable<any> {
return this.processedData.asObservable();
}
}
An example call in another component:
this.outputService.doCalculation([1, 2, 3, 4, 5, 6], [2, 4, 5, 8, 3], 2);