Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying use a class with a constructor object, in another class. But how do I call that class correctly? eg: How do i use Class 1, in Class 2?

The example below is creating an object, from a response from an axios call. The _object should be whatever I get from getData(). Im not sure if this is the right approach. But how do i then call this class with the constructor, in another class? Ideally I want to be able to query the properties of the object, and use them in the other class, but Im not sure how to call the class properly.

Class 1:

export class MyClass {

    private _object: any;

    constructor(object: any) {
        this._object = object;
    }

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

}

Trying to use this in another class, with constructor object:

Class 2:

new MyClass(object);  // cannot find name object

or

new MyClass();  // without constuctor object, Expected 1 arguments, but got 0. An argument for 'object' was not provided.'

Ive asked related question here: return properties of constructor object

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
138 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your constructor requires an object as its argument. So to construct an object of MyClass, you'll need to do something like:

let obj = new MyClass({}) // construct with an empty object as the arg
// or:
let argObj = {a: 123}
let obj = new MyClass(argObj)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...