我处于这种情况,我以嵌套格式编写api调用。鉴于api调用后者的要求取决于前者的结果,是否有更好的方法来处理这个问题?我特别希望找到一个干净而优雅的解决方案,以便更好地组织呼叫,这样我就可以避免嵌套
更新:
这是代表我想要更好地处理的真实情况的代码:
api调用表示应用程序的动作/流程应该是的顺序。有没有更好的方法来处理嵌套调用?
dummyMethod(){
activeModal.result.then((modalResult)=>{
var payload = {
id:modalResult.id,
value:modalResult.value,
}
this.dataService.updateRelationship(payload)
.subscribe(response =>{
if(response.success){
var payload:{
otherId: response.someId,
otherValue:response.someValue
}
this.dataService.doCleanup(payload)
.subscribe(otherResponse => {
if(otherResponse.success){
var anotherPayload:{
someOtherId: otherResponse.otherId,
someOtherValue: otherResponse.otherValue,
}
this.dataService.fetchResults(anotherPayload)
.subscribe(results => {
// do something with results
}, error => {
// log error
});
}}, otherError => {
// log error
});
}
}, error => {
// log error
});
});
}
您通常使用pipe和flatMap(或任何适合您用例的运算符):
this.http.get(url)
.pipe(
flatMap((data: any) => this.http.get(url + data.whatever)),
flatMap((data: any) => /* ... */)
)
.subscribe((data: any) => {
console.log(data);
});
对于不相互依赖的请求,您可以使用zip
zip(this.http.get('foo'), this.http.get('bar'))
.subscribe(([foo, bar]) => ...)
您可以尝试使用promise
,async
和await
。我发现这篇文章描述了你要做的事情:https://medium.com/@balramchavan/using-async-await-feature-in-angular-587dd56fdc77
所以你试图通过嵌套来做这样的事情:
getConditionalDataUsingPromise() {
this.httpClient.get<Employee>(this.url).toPromise().then(data => {
console.log('First Promise resolved.')
if (data.id > 5) {
let anotherUrl = 'http://dummy.restapiexample.com/api/v1/employee/23';
this.httpClient.get<Employee>(anotherUrl).toPromise().then(data => {
this.conditionalPromiseResult = data;
console.log('Second Promise resolved.')
});
}
});
}
你会想要像这样重写它:
async getConditionalDataUsingAsync() {
let data = await this.httpClient.get<Employee>(this.url).toPromise();
if (data.id > 5) {
let anotherUrl = 'http://dummy.restapiexample.com/api/v1/employee/23';
this.conditionalAsyncResult = await this.httpClient.get<Employee>(anotherUrl).toPromise();
}
console.log('No issues, I will wait until promise is resolved..');
}