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

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

本文介绍了使用构造函数从对象返回属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

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

其他班级

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

推荐答案

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

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.

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

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.

这篇关于使用构造函数从对象返回属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:58