如何在Angular 12中同步进行HTTP帖子调用
我需要使用POST方法调用API,这取决于我需要进一步实施业务逻辑的响应。 以下是代码片段:
GetSuffixList(_LinesToMove: string[], NbrOfLinesForMove:string): void {
let getSuffixReq = {
sys: this.workItemGetResponse.getTagValue("SYS"),
icn: this.workItemGetResponse.getTagValue("ICN"),
suffix: this.calculateFinalizeResponse.body.srvcRspn.icnSufx,
ClaimType: this.workItemGetResponse.getTagValue("CLMTYP"),
authEngTkn: this._service.authToken.token,
adjId: this._service.loginRequest.UserId,
LinesToMove: _LinesToMove,
NumberOfLinesToMove: NbrOfLinesForMove
};
this._service.GetSuffixList(getSuffixReq).subscribe(
getSuffix => {
this.getSuffixListResp = getSuffix;
console.log(getSuffix);
},
err => {
console.log("Error at GetSuffixList");
console.log(err.error);
}
);
}
挑战是它异步执行,在主要组件中,它继续执行剩余的代码行,这需要上述称为API的响应。 可能缺乏知识,我无法实现它。 请有人帮忙。
I have a requirement to call an API using post method, depending on the response i need to further implement business logic.
Below is code snippet:
GetSuffixList(_LinesToMove: string[], NbrOfLinesForMove:string): void {
let getSuffixReq = {
sys: this.workItemGetResponse.getTagValue("SYS"),
icn: this.workItemGetResponse.getTagValue("ICN"),
suffix: this.calculateFinalizeResponse.body.srvcRspn.icnSufx,
ClaimType: this.workItemGetResponse.getTagValue("CLMTYP"),
authEngTkn: this._service.authToken.token,
adjId: this._service.loginRequest.UserId,
LinesToMove: _LinesToMove,
NumberOfLinesToMove: NbrOfLinesForMove
};
this._service.GetSuffixList(getSuffixReq).subscribe(
getSuffix => {
this.getSuffixListResp = getSuffix;
console.log(getSuffix);
},
err => {
console.log("Error at GetSuffixList");
console.log(err.error);
}
);
}
Challenge here is it executes asynchronously and in main component it continues executing remaining lines of code which requires response of the above called API.
May be lack of knowledge i was not able to achieve it.
Please someone help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是使用RXJS lastValuefrom()和异步等待的简单解决方案。
从lastvaluefrom:通过订阅可观察到的可观察到的承诺,等待它完成,并从观察到的流中获得最后一个值,将其转换为承诺。
这取代了.topromise()方法。我一直很喜欢将我的httpclient订阅转换为承诺,因为您并没有真正订阅宁静的端点。
您甚至可以在lastValue从返回诺言之后扔一个.catch()()!这也是您要等待的原因;)
希望这会有所帮助!
文档: https://rxjs.dev/api/api/index/index/index/function/function/lastvaluefrom
Here is an easy solution using rxjs lastValueFrom() with async await.
lastvalueFrom: Converts an observable to a promise by subscribing to the observable, waiting for it to complete, and resolving the returned promise with the last value from the observed stream.
This replaced the .toPromise() method. I was always a fan of converting my httpClient subscription's to promises, since your not really subscribing to a RESTful endpoint.
You can even throw a .catch() after, since lastValueFrom returns a promise! That is also the reason you get to use await ;)
Hopefully this helps!
Docs: https://rxjs.dev/api/index/function/lastValueFrom