![](/img/trans.png)
[英]How to wait for asynchronous http subscription to complete in multilevel nested function
[英]How to make a function to wait until asynchronous function (http post request) to complete in angular 2?
我有一个函数,它依赖于 http post 请求函数的响应。 但是因为 os post 请求是异步的,所以函数 get 在 get post 请求响应之前执行。 所以我收到错误。
任何人都可以提供解决方案,使等待功能,直到发布请求在角度 2 中完成吗?
提前致谢。
例如,如果您有一个进行服务调用的函数,并且您想在该服务调用成功执行后再调用一个函数,那么您需要像这样调用第一个函数的 .susbcribe 中的第二个函数
this.serivce.servcefunction(yourrequest).subscribe
(data =>
{
secondfunctiontoexecute();
},
Error =>
{
alert("failed")
})
post 请求返回一个 Observable,因此您需要订阅该 Observable。
let post = {JSON to POST};
this.http.post(this.url, JSON.stringify(post))
.subscribe(response => {
functionToExecute()
},
(error: Response) => {
if (error.status === STATUS_ERROR) {
handleExpectedError();
} else {
handleUnexpectedError();
}
});
您应该提取一个可重用的错误处理方法,这样您就不必在您编写的每个 POST 请求中为不同的 http 错误编写相同的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.