在下面的代码中,getElements函数没有等待getSChema()函数完成,它是异步运行的,我如何进行同步函数调用,我想等到getschema()函数执行完成< / p>
getSChema()
{
this.getPdiSchema(this.ApplicationsComponent.selectedApplication)
.subscribe((res: any) => {
console.log("res:"+res);
this.resdata=res;
}
);
}
getElements() {
let elements:any[];
let complexType:any[];
let sequence:any[];
let elements1:any[];
let elements2:any[];
let complexType1:any[];
let sequence1:any[];
let elementsArray: PdiSchemaBase<any>[] = [];
this.getSChema(); //wait until getSchema execution is complete
elements = this.resdata["xs:schema"]["xs:element"]
complexType = elements[0]["xs:complexType"];
sequence = complexType[0]["xs:sequence"];
elements1 = sequence[0]["xs:element"];
complexType1 = elements1[0]["xs:complexType"];
sequence1 = complexType1[0]["xs:sequence"];
this.pdiElements = sequence1[0]["xs:element"];
let i=1;
for (let element of this.pdiElements)
{
console.log("printing elements:"+i)
if(element["$"].type !== undefined)
{
console.log("element.type:"+element["$"].type)
elementsArray.push(new TextboxElements({
key: element["$"].name,
label: element["$"].name,
required: true,
order: i
}))
}
i=i + 1;
}
return elementsArray.sort((a, b) => a.order - b.order);
}
如果我添加一个Observable并订阅它,则无法从getElements返回值
getElements()
{
let elementsArray: PdiSchemaBase<any>[] = [];
console.log("calling get schema:");
console.log("this.selectedApplication:"+this.ApplicationsComponent.selectedApplication);
this.getPdiSchema(this.ApplicationsComponent.selectedApplication)
.subscribe((res: any) => {
console.log("res:"+res);
//code here....
}
);
// this return doens't seems to work
return elementsArray.sort((a, b) => a.order - b.order);
}
答案 0 :(得分:1)
最好更改getSChema()
以返回observable。
getSChema() {
return this.getPdiSchema(this.ApplicationsComponent.selectedApplication);
}
然后在getElements()
中您可以订阅它
getElements() {
...
this.getSChema().subscribe((res: any) => {
// code to execute once it's completed
})
}
对评论的回应:
从getSChema()
移除getElements()
,而在您致电getElements()
的地方使用以下内容:
this.getSChema().subscribe((res: any) => {
this.resdata = res;
this.elements = this.getElements();
});
答案 1 :(得分:0)
如果你想返回return elementsArray.sort((a, b) => a.order - b.order);
,你可以使用map
而不是subscribe
,即返回一个observable和期望结果可以订阅的方法,所以在某行中。 ...
getElements() {
return this.getSchema()
.map(res => {
// do your stuff here, then....
return elementsArray.sort((a, b) => a.order - b.order);
});
}
正在调用getElements
...
myFunction() {
this.getElements()
.subscribe(data => console.log(data));
}
或者您也许可以直接致电getSchema()
,我会这样做:)