我正在调用虚拟Web API来填充类的变量以进一步使用它,因为我遇到了一个使我感到困惑的奇怪情况
export class myClass implements OnInit{
data : any;
constructor (private http:HttpClient){}
ngOnInit(){
this.http.get("http://dummy.restapiexample.com/api/v1/employee/82342").subscribe(e=>this.data = e);
alert("beforeConsole");
console.log(this.data);
var size = Object.keys(this.data).length;
alert(size);
}
}
仅当我使用alert
时才填充变量数据(仅用于检查)。如果我删除了alert("beforeConsole");
,然后控制台给了我未定义的内容。
我无法理解这一点。请提出实际情况
答案 0 :(得分:0)
Http.get返回一个Observable,并且是异步的。 您的console.log会在请求有时间处理之前运行。
将console.log移动到您的订阅中,因为一旦发出可观察对象,它将运行。
this.http.get("http://dummy.restapiexample.com/api/v1/employee/82342")
.subscribe(e => {
this.data = e;
console.log(this.data);
var size = Object.keys(this.data).length;
});
答案 1 :(得分:-1)
我建议您使用异步等待。
ngOnInit(): void { this.initialize(); }
async initialize(): Promise<void> {
try {
this.data = await this.http.get("http://dummy.restapiexample.com/api/v1/employee/82342").toPromise();
console.log(this.data);
} catch (e) { console.error(e); }
}