MergeMap - 串联请求
import {HttpClient} from '@angular/common/http';import {mergeMap} from 'rxjs';@Component({
...
})export classHttpComponentimplementsOnInit{
constructor(privatehttp: HttpClient) { }
ngOnInit() {
// 串联请求, 前面请求会影响后面的请求,前面请求未请求到,后面请求中断; const httpThis = this;
httpThis.http.get('/api/token').
pipe(
map(token=> {
return token;
}),
mergeMap((tokenRes:any) => { // tokenRes接收的是token数据 return httpThis.http.get(`/api/user?token=${tokenRes}`)
.pipe((user) => {
return user;
});
}),
mergeMap((userRes:any) => { // userRes接收的是user数据 return httpThis.http.get(`api/data?user=${userRes}`)
.pipe((data) => {
return data;
});
}))
.subscribe((resp) => { // resp接收的是data数据 console.log('最终结果resp是最后一个mergeMap的data');
});
}
}
2. ForkJoin - 并联请求
import {HttpClient} from '@angular/common/http';import {forkJoin} from 'rxjs';@Component({
...
})export classHttpComponentimplementsOnInit{
constructor(private http: HttpClient) { }
ngOnInit() {
// 并联请求 const post1 = this.requestData1();
const post2 = this.requestData2();
forkJoin([post1, post2])
.subscribe((data: any) => {
const postResult1 = data[0]; // '/api/post1的返回结果' const postResult2 = data[1]; // '/api/post2的返回结果' });
}
// 并联请求1 requestData1() {
return this.http.get('/api/post1')
.pipe((data) => {
return data;
});
}
// 并联请求2 requestData2() {
return this.http.get('/api/post2')
.pipe((data) => {
return data;
});
}
}
网友评论