[英]angular2 2 async call
Angular2, typescript Angular2,打字稿
I have a component that displays 1 object at a time from the server. 我有一个组件,一次从服务器显示1个对象。
On the click of a button, the form does some action on the object, sends data to the server. 单击按钮后,表单会对对象执行某些操作,然后将数据发送到服务器。 Immediately in the next line, the next object is got. 立即在下一行中,得到下一个对象。
this.rawS.updateTags({......}); //Update object
this.candidateC.footerNavigateTo(.....);//Get next object
But there is a race condition where ajax to get next object reaches the server before the updateTags ajax reaches the server. 但是在竞争条件下,要获取下一个对象的ajax在updateTags ajax到达服务器之前已到达服务器。
Code of updateTags is 更新代码的代码为
updateTags(rawCandidate) {
this.baseAjaxService.doPost(this.baseUrl + 'tags/update', rawCandidate)
.subscribe(data => {
console.log(data);
});
}
Code for doPost is doPost的代码是
doPost(url, inputParamJSON){
let httpResponse = this.http
.post(url, inputParamJSON, this.options)
.map(this.extractData)
.catch(this.handleAjaxError);
return httpResponse;
}
The route for 'continue_screening' has a route resolver which brings the next object. “ continue_screening”的路由具有一个路由解析器,该路由解析器会带来下一个对象。
How can I ensure that footerNavigateTo() runs only after updateTags has completed its full cycle? 我如何确保footerNavigateTo()仅在updateTags完成其整个周期之后运行?
If what you want is to have different behaviours depending on where the function updateTags(rawCandidate)
is called, I propose the following solution: 如果您希望根据调用updateTags(rawCandidate)
函数的位置而具有不同的行为,那么我提出以下解决方案:
updateTags(rawCandidate, action) {
this.baseAjaxService.doPost(this.baseUrl + 'tags/update', rawCandidate)
.subscribe(
data => {
action(data);
},
error => {
console.log("error"); //handle error here
});
}
Then you can call the function like this: 然后,您可以像下面这样调用函数:
updateTags(rawCandidate, function(data){
console.log(data);
this.candidateC.footerNavigateTo(.....);//here you can use data
});
What you want to achieve here is to chain your two http calls, make them dependents somehow. 在这里要实现的是将两个http调用链接起来,使它们以某种方式依赖。 In Angular 1.X it would be done using promise but with AngularJS 2 you can achieve that using flatMap . 在Angular 1.X中,可以使用promise来完成,但是使用AngularJS 2可以使用flatMap来实现。
See this link http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http at Dependent calls section. 请参阅“ 相关调用”部分中的此链接http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http 。
PS : As indicated in this post ( Combining promises in Angular 2 ) you can also use toPromise()
to transform your Observable (ie your async http call) into a Promise, if you are more familiar with it. PS:如本文所述( 在Angular 2中组合诺言 ),您也可以使用toPromise()
将Observable(即,异步http调用)转换为Promise,如果您对此更加熟悉的话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.