问题
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
回答1:
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)
来源:https://stackoverflow.com/questions/56724526/using-classes-with-constructor-objects