我正在尝试填充数组zvols
,其中包含zvols列表路径的名称。问题是我在成功调用电话后得到一个空数组
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable, Subject, Subscription } from 'rxjs/Rx';
import { EntityUtils } from '../pages/common/entity/utils'
import { RestService, WebSocketService } from '../services/';
@Injectable()
export class VmService {
protected volume_resource_name: string = 'storage/volume'
constructor(protected rest: RestService){
};
getStorageVolumes() {
let zvols: Array<any> = [];
this.rest.get(this.volume_resource_name , {}).subscribe((res) => {
let data = new EntityUtils().flattenData(res.data);
for (let zvol_obj of data){
if (zvol_obj.type === 'zvol') {
zvols.push(zvol_obj.path);
}
}
console.log("BEFORE:" + zvols);
});
console.log("AFTER:" + zvols);
return zvols;
}
}
我可以看到控制台打印
AFTER:
main.bundle.js:744 Unknown message: Object {msg: "ready", subs: Array(1)}
vm.service.ts:26 BEFORE:tank-a/ds-a/zvol-a,tank-b/ds-b/zvol-b
我对这种行为感到困惑。 :(
答案 0 :(得分:1)
在您的代码中:
this.rest.get(this.volume_resource_name , {}).subscribe((res) => {
let data = new EntityUtils().flattenData(res.data);
for (let zvol_obj of data){
if (zvol_obj.type === 'zvol') {
zvols.push(zvol_obj.path);
}
}
console.log("BEFORE:" + zvols);
});
console.log("AFTER:" + zvols);
AFTER
在 BEFORE
行之前执行。这是异步编程的本质。
使用调试器并逐步执行代码以查看其工作原理。