我在我的angular2 +组件中做了一个函数,输出首先出现,该函数随后运行,因此,我想要的适当输出随后出现。该函数将变量参数和http请求一起传递给后端NodeJS。并返回结果。我想找到我能找到的长度。但是,我想通过传递多个参数多次调用此参数。所以我将其定义为异步函数。代码是-
app.component.ts
// Function 1
getNodesCount() {
console.log("INSIDE getNodesCount()")
if (this.selectedAPIName.length == 1) {
this.nodesObjQ1 = {
'relationObj': this.menuItem,
'nodeValue1': this.selectedAPIName[0]
}
this.callFunctionCount(this.nodesObjQ1).then((rs: any[])
=> {
this.nodesObjL1 = rs;
});
console.log("this.nodesObjL1 =", this.nodesObjL1)
}
}
//Function 2
async callFunctionCount(trueNodesObject) {
console.log("nodesObj =", trueNodesObject);
await new Promise(next => {
this.http.get("http://localhost:3003/seekExtraction/nodesObj/" +
JSON.stringify(trueNodesObject))
.map(Response => Response)
.catch((err) => {
console.log("err =", err)
return Observable.throw(err);
})
.subscribe((res: Response) => {
console.log("XXXXXXXXXXXX Response on /seekExtraction",
res);
this.nodesInfo = res;
this.nodesLength = this.nodesInfo.records.length
next()
})
});
console.log("return this.nodesLength =", this.nodesLength)
return this.nodesLength;
}
主要产出-
this.nodesObjL1 = undefined
return this.nodesLength = 2
请帮助检索该值-
this.nodesObjL1
此值之后
this.nodesInfo.records.length= 2
答案 0 :(得分:1)
实际的最小示例将有助于确保干净的代码...但是尝试一下...
getData = function (trueNodesObject) {
return new promise((resolve, reject) => {
this.http.get("http://localhost:3003/seekExtraction/nodesObj/" +
JSON.stringify(trueNodesObject))
.map(Response => Response)
.catch((err) => {
console.log("err =", err)
return Observable.throw(err);
reject(err);
})
.subscribe((res: Response) => {
console.log("XXXXXXXXXXXX Response on /seekExtraction",
res);
this.nodesInfo = res;
this.nodesLength = this.nodesInfo.records.length
resolve(this.nodesLength);
next()
});
})
}
async function callFunctionCount(trueNodesObject) {
console.log("nodesObj =", trueNodesObject);
const someVal = await getData(trueNodesObject);
console.log("return this.nodesLength =", someVal)
}