如何在 Angular 2 中链接 HTTP 调用?
How can I chain HTTP calls in Angular 2?
我是 Angular 2 和 HTTP Observables 的新手。我有一个调用 HTTP 服务的组件和 returns 一个 Observable。然后我订阅了那个 Observable,它工作正常。
现在,我想在那个组件中,在调用第一个 HTTP 服务之后,如果调用成功,调用另一个 HTTP 服务和 return Observable。因此,如果第一次调用不成功,组件 returns 是 Observable,与它相对的是第二次调用的 returns 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 运算符的更多信息here
使用 rxjs 来完成这项工作是一个很好的解决方案。容易阅读吗?我不知道。
另一种更易读(在我看来)的方法是使用 await/async.
示例:
async getContrat(){
// Get the customer
const customer = await this.http.get('./customer.json').toPromise();
// Get the contract from the 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
}
您也可以链接 Promise。根据这个例子
<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>
我是 Angular 2 和 HTTP Observables 的新手。我有一个调用 HTTP 服务的组件和 returns 一个 Observable。然后我订阅了那个 Observable,它工作正常。
现在,我想在那个组件中,在调用第一个 HTTP 服务之后,如果调用成功,调用另一个 HTTP 服务和 return Observable。因此,如果第一次调用不成功,组件 returns 是 Observable,与它相对的是第二次调用的 returns 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 运算符的更多信息here
使用 rxjs 来完成这项工作是一个很好的解决方案。容易阅读吗?我不知道。
另一种更易读(在我看来)的方法是使用 await/async.
示例:
async getContrat(){
// Get the customer
const customer = await this.http.get('./customer.json').toPromise();
// Get the contract from the 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
}
您也可以链接 Promise。根据这个例子
<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>