我创建了一个类,该类需要调用其他类并获取数据
E.g
import { SC } from "./svc/service";
export default class myClass{
//Here define the variable
sc: SC;
async initializing() {
// Here I’ve created the instance
this.sc = new SC();
this.sc.getServices()
}
Async testValue{
//Now when I call to the function from here in debug I see that this inside `SERVICE_INSTANCE` is empty , why ????
this.sc.getServices()
}
}
export default class SC{
SERVICE_INSTANCE: string[] = [];
async getServices(
//If the function already called I’m returning the value
If(this.SERVICE_INSTANCE){
return this.SERVICE_INSTANCE;
}
….
//here when the function called first I got data and assign the service instance to avoid hits
this.SERVICE_INSTANCE = GetData();
}
}
为什么当我第二次调用函数getService
时,我得到了未定义的If(this.SERVICE_INSTANCE){
,为什么?
我可以将属性存储在全局级别,但我想避免它,我不会创建另一个实例,只在initilizing
中创建一个实例,并在testValue
函数中使用它。。。
第二次调用中this
未定义的问题
由于SERVICE_INSTANCE的类型为string[],因此您的检查if(this.SERVICE_INSTANCE)
将始终为true,这就是它始终返回空数组的原因。
您需要检查if(this.SERVICE_INSTANCE.length)