MergeMap - 串聯(lián)請求
import {HttpClient} from '@angular/common/http';import {mergeMap} from 'rxjs';@Component({
? ...
})export classHttpComponentimplementsOnInit{
? constructor(privatehttp: HttpClient) { }
? ngOnInit() {
? ? // 串聯(lián)請求, 前面請求會(huì)影響后面的請求砰琢,前面請求未請求到,后面請求中斷;? ? const httpThis = this;
? ? httpThis.http.get('/api/token').
? ? ? pipe(
? ? ? map(token=> {
? ? ? ? return token;
? ? ? }),
? ? ? mergeMap((tokenRes:any) => { // tokenRes接收的是token數(shù)據(jù)? ? ? ? return httpThis.http.get(`/api/user?token=${tokenRes}`)
? ? ? ? ? .pipe((user) => {
? ? ? ? ? ? return user;
? ? ? ? ? });
? ? ? }),
? ? ? mergeMap((userRes:any) => { // userRes接收的是user數(shù)據(jù)? ? ? ? return httpThis.http.get(`api/data?user=${userRes}`)
? ? ? ? ? .pipe((data) => {
? ? ? ? ? ? return data;
? ? ? ? ? });
? ? ? }))
? ? ? .subscribe((resp) => { // resp接收的是data數(shù)據(jù)? ? ? ? console.log('最終結(jié)果resp是最后一個(gè)mergeMap的data');
? ? ? });
? }
}
2. ForkJoin - 并聯(lián)請求
import {HttpClient} from '@angular/common/http';import {forkJoin} from 'rxjs';@Component({
? ...
})export classHttpComponentimplementsOnInit{
? constructor(private http: HttpClient) { }
? ngOnInit() {
? ? // 并聯(lián)請求? ? const post1 = this.requestData1();
? ? const post2 = this.requestData2();
? ? forkJoin([post1, post2])
? ? ? .subscribe((data: any) => {
? ? ? ? const postResult1 = data[0]; // '/api/post1的返回結(jié)果'? ? ? ? const postResult2 = data[1]; // '/api/post2的返回結(jié)果'? ? ? });
? }
? // 并聯(lián)請求1? requestData1() {
? ? return this.http.get('/api/post1')
? ? ? .pipe((data) => {
? ? ? ? return data;
? ? ? });
? }
? // 并聯(lián)請求2? requestData2() {
? ? return this.http.get('/api/post2')
? ? ? .pipe((data) => {
? ? ? ? return data;
? ? ? });
? }
}