![](/img/trans.png)
[英]Angular2 - How to chain async service calls (http requests) in a component?
[英]How to chain Http calls in Angular2?
我是Angular2和Http Observable的新手。 我有一个调用Http服务并返回Observable的组件。 比我订阅Observable,它工作正常。
现在,我希望在该组件中,在调用第一个Http服务之后,如果调用成功,则调用其他Http服务并返回该Observable。 因此,如果第一次调用不成功,则组件返回Observable,而它返回Observable的第二次调用。
所以,问题是,链接Http调用的最佳方法是什么? 有没有优雅的方式,比如monads?
您可以使用mergeMap
运算符执行此操作。
Angular 4.3+(使用HttpClientModule
)和RxJS 6+
import { mergeMap } from 'rxjs/operators';
this.http.get('./customer.json').pipe(
mergeMap(customer => this.http.get(customer.contractUrl))
).subscribe(res => this.contract = res);
Angular <4.3(使用HttpModule
)和RxJS <5.5
导入操作符map
和mergeMap
,然后您可以链接两个调用,如下所示:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
this.http.get('./customer.json')
.map((res: Response) => res.json())
.mergeMap(customer => this.http.get(customer.contractUrl))
.map((res: Response) => res.json())
.subscribe(res => this.contract = res);
这里有更多细节: http : //www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
有关mergeMap运算符的更多信息,请参见此处
使用rxjs来完成这项工作是一个非常好的解决方案。 它易于阅读吗? 我不知道。
另一种方法是执行此操作并且更具可读性(在我看来)是使用await / async 。
示例:
async getContrat(){
//get the customer
const customer = await this.http.get('./customer.json').toPromise();
//get the contract from url
const contract = await this.http.get(customer.contractUrl).toPromise();
return contract; // you can return what you want here
}
然后叫它:)
this.myService.getContrat().then( (contract) => {
// do what you want
});
或者在异步功能中
const contract = await this.myService.getContrat();
您还可以使用try / catch来管理错误:
let customer;
try {
customer = await this.http.get('./customer.json').toPromise();
}catch(err){
console.log('Something went wrong will trying to get customer');
throw err; // propagate the error
//customer = {}; //it's a possible case
}
你也可以链接Promises。 按照这个例子
<html>
<head>
<meta charset="UTF-8">
<title>Chaining Promises</title>
</head>
<body>
<script>
const posts = [
{ title: 'I love JavaScript', author: 'Wes Bos', id: 1 },
{ title: 'CSS!', author: 'Chris Coyier', id: 2 },
{ title: 'Dev tools tricks', author: 'Addy Osmani', id: 3 },
];
const authors = [
{ name: 'Wes Bos', twitter: '@wesbos', bio: 'Canadian Developer' },
{ name: 'Chris Coyier', twitter: '@chriscoyier', bio: 'CSS Tricks and Codepen' },
{ name: 'Addy Osmani', twitter: '@addyosmani', bio: 'Googler'},
];
function getPostById(id) {
// create a new promise
return new Promise((resolve, reject) => {
// using a settimeout to mimic a database/HTTP request
setTimeout(() => {
// find the post we want
const post = posts.find(post => post.id == id);
if (post) {
resolve(post) // send the post back
} else {
reject(Error('No Post Was Found!'));
}
},200);
});
}
function hydrateAuthor(post) {
// create a new promise
return new Promise((resolve, reject) => {
// using a settimeout to mimic a database/http request
setTimeout(() => {
// find the author
const authorDetails = authors.find(person => person.name === post.author);
if (authorDetails) {
// "hydrate" the post object with the author object
post.author = authorDetails;
resolve(post);
} else {
reject(Error('Can not find the author'));
}
},200);
});
}
getPostById(4)
.then(post => {
return hydrateAuthor(post);
})
.then(post => {
console.log(post);
})
.catch(err => {
console.error(err);
});
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.