1. MergeMap - 串聯請求
-
后一個請求需要前一個請求的返回結果時,需要使用串聯請求。
-
可以使用
MergeMap
實現, 優勢是減少嵌套,優化代碼;
代碼如下:
import {HttpClient} from '@angular/common/http'; import {mergeMap} from 'rxjs'; @Component({ ... }) export class HttpComponent implements OnInit { constructor(private http: 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 - 並聯請求
-
多個請求,無所謂先后順序,等到全部請求完成后執行一定的操作時,需要使用並聯請求;
-
可以使用ForkJoin,和promise方法效果一樣,好處是:可以減少嵌套,優化代碼;
代碼如下:
import {HttpClient} from '@angular/common/http'; import {forkJoin} from 'rxjs'; @Component({ ... }) export class HttpComponent implements OnInit { 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; }); } }