使用构造函数从对象返回属性

时间:2019-06-23 15:58:10

标签: typescript constructor axios

我有一个从函数创建的构造函数对象,该函数是axios get请求的响应。然后,我想返回该对象的属性,并将某些值保存为另一个类中的字符串。例如:我希望能够保存值:response.data.nameresponse.data.address。到目前为止,我在尝试获取这些值时变得不确定。

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;
   }
}

其他班级

const temp = new MyClass(Object).getName(); //  undefined
const temp = new MyClass({}).getName(); //  undefined

2 个答案:

答案 0 :(得分:0)

MyClass.getCurrentData()创建MyClass的新实例,该实例将包含所有获取的数据。但是,此数据仍保留在该实例上,它不是静态的。

此外,我看不到异步函数getCurrentData的任何等待调用,因此可能是只有在执行getName()检查调试后才能执行。

答案 1 :(得分:0)

我的问题如下解决:

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