问题
I have a constructor object that is created from a function, which is the response of a axios get request. I then want to return properties of that object and save some of the values to be used as a string in another class. eg: I want to be able to save values: response.data.name, response.data.address from the resposne. So far, im getting undefined when trying to get those values.
export class MyClass {
private _myobject: any;
constructor(myobject: any) {
this._myobject = myobject;
}
public static async getData() {
return axios.get(url)
.then(response => response.data)
.catch((error) => {
console.log(error);
});
}
public static async getCurrentData() {
return new MyClass(await this.getData());
}
getName() {
console.log(this._myobject.name);
return this._myobject.name;
}
}
other class
const temp = new MyClass(Object).getName(); // undefined
const temp = new MyClass({}).getName(); // undefined
回答1:
MyClass.getCurrentData() creates a new instance of MyClass, which will contain any fetched data. This data however remains on this instance, it is not static.
Also, I don't see any await calls for the async function getCurrentData, so it can be that it is executed only after you're doing your getName() checks for debugging.
回答2:
my issue was solved as below:
export class MyClass {
private _object: any;
private constructor(object: any) {
this._object = object;
}
private static async getData() {
return axios.get(url)
.then(response => response.data)
.catch((error) => {
console.log(error);
});
}
// returns data from get request, adds to constructor of same class
public static async getCurrentData() {
return new MyClass(await MyClass.getData());
}
public getName() { // getter uses constructor
return this._object.name;
}
}
export class Artifact {
public async addDataToReport() {
const myClass = await MyClass.getCurrentData(); // create new instance of MyClass
const name = myClass.getName(); // call getter from myClass
console.log(name);
}
}
来源:https://stackoverflow.com/questions/56725579/return-properties-from-object-using-constructor-function