I have a class with this structure:
class MyClass{
json;
constructor(){
}
}
I would like to assign my "json" property form an API request in the constructor as an Array.
I've tried all sorts of methods and even copied code snippets directly from other forums. In the debugger and from console.log()
, I've confirmed that I'm actually getting a response and in the Promise.prototype.then()
I was able to use the result. But I just can't get it assigned to a class property.
These examples don't work:
class MyClass{
json;
constructor(){
fetch(url)
.then(response => response.json())
.then(json => {
this.json = json; // I've tried using "self" when not using the "=>" operator
});
}
}
class MyClass{
json;
constructor(){
fetch(url)
.then(response => response.json())
.then(json => {
this._setJson(json);
});
}
_setJson(json){
this.json = json;
}
}
I've also tried initializing json
as an Array and using this.json.push(json)
or returning json
as an Object.
All the times this.json
never gets assigned and I get ReferenceError: json is not defined↵ at eval (...
I would like it to be assigned but clearly, it isn't. Also, I'm using Chrome 75 if that makes any difference. - Thanks