我对帖子方法有一些问题。我总是在我的临时段中获得空的段数据对象。我对数字做同样的事情,这是工作。订阅中的变量结果是分段数据,在控制台中.log我收到预期的响应。怎么可能?我的方法:
onGetSegmentsClick(size: number) {
debugger;
if (size > 0) {
let counter = 0;
let temporarySegment = new SegmentData();
while (counter < size) {
this.segmentService.getSegment(counter + 1, this.elementId, this.documentId).subscribe(result => {
console.log("get segment request is sended");
temporarySegment = result;
console.log("gotten message is:", result);
});
ModalComponent.segmentsCollection.push(new SegmentData());
ModalComponent.segmentsCollection[ModalComponent.segmentsCollection.length - 1] =
ModalComponent.newer.TemporaryObjectEqualizer(temporarySegment);
ModalComponent.segmentsCollection[ModalComponent.segmentsCollection.length - 1].SegmentDataId =
counter + 1;
counter++;
}
}
}
我的getSegment方法:
getSegment(segmentId: number, elementId: string, documentId: string) {
let headers = new Headers();
headers.append("Content-type", "application/json");
let input = {
"elementId": elementId,
"documentId": documentId,
"segmentNumber": segmentId
}
let sendingData = JSON.stringify(input);
let urlPost = "https://localhost:44375/api/data/SendSegmentData";
let output = new AsyncSubject<SegmentData>();
let options = new RequestOptions({
headers: headers,
method: RequestMethod.Post,
url: urlPost
});
this.http.post(urlPost, sendingData, options)
.subscribe(result => {
output.next(result.json());
output.complete();
});
return output;
}
类段客户端上的数据等于服务器上的相关类。我的回答被完美地解析了。如何解决这个问题?提前谢谢((
调用结束,因此循环将运行而无需等待订阅完成并运行。下面的代码被更改为将所有代码放在订阅调用中。
onGetSegmentsClick(size: number) {
debugger;
if (size > 0) {
let counter = 0;
let temporarySegment = new SegmentData();
while (counter < size) {
this.segmentService.getSegment(counter + 1, this.elementId, this.documentId).subscribe(result => {
console.log("get segment request is sended");
temporarySegment = result;
console.log("gotten message is:", result);
ModalComponent.segmentsCollection.push(new SegmentData());
ModalComponent.segmentsCollection[ModalComponent.segmentsCollection.length - 1] =
ModalComponent.newer.TemporaryObjectEqualizer(temporarySegment);
ModalComponent.segmentsCollection[ModalComponent.segmentsCollection.length - 1].SegmentDataId =
counter + 1;
counter++;
});
}
}
}
其他人已经解释了正在发生的事情。 在 while 循环中遵循subscribe()
的代码实际上在订阅函数之前运行,因为该函数仅在响应从服务器返回后异步运行。所以当你尝试使用temporarySegment
的值时,它仍然是空的。
你问:
如何等到回复回来?
您可以使用异步/等待编码模式使异步代码与过程的其余部分保持一致。 首先将async
修饰符添加到函数声明中:
async onGetSegmentsClick(size:number){ ...
然后将可观察链转换为承诺,并使用 await
修饰符告诉 JS 引擎等待结果后再继续:
temporarySegment = await this.segmentService.getSegment(...).toPromise();
// here you can use temporarySegment immediately
查看文档