後一個請求須要前一個請求的返回結果時,須要使用串聯請求。api
能夠使用MergeMap
實現, 優點是減小嵌套,優化代碼;promise
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'); }); } }
多個請求,無所謂前後順序,等到所有請求完成後執行必定的操做時,須要使用並聯請求;post
能夠使用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; }); } }