如果您的服务是Observable
基于而不是Promise
你可以做forkJoin
。它并行运行所有可观察的序列。
对于 RxJS 版本
import 'rxjs/add/observable/forkJoin';
确保import forkJoin
from rxjs
library
Observable.forkJoin(myService.getCall(),
myService.postCall(),
...)
.subscribe((res) => {
res[0] // this is first service call response,
res[1] // this is second service call response
...
});
或者,如果您希望它是连续的,请执行第一个调用,然后完成第二个调用。
myService.getCall().subscribe((response) => {
// handle response
}, (error) => {
// handle error here
}, () => {
// this is complete block and it is triggered when obervable is complete
myService.postCall();
}
EDIT:适用于 RxJS 6 及以上版本forkJoin
已经改变
Service:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { forkJoin, Observable } from 'rxjs';
@Injectable()
export class MyService {
constructor(private http: HttpClient) {
}
getAndPost(): Observable<any> {
return forkJoin(
this.http.get('/api/get'),
this.http.post('/api/post')
);
}
}
成分:
firstResponse: any;
secondResponse: any;
constructor(private myService: MyService) {
}
myFunction(): void {
this.myService.getAndPost().subscribe((res) => {
this.firstResponse = res[0],
this.secondResponse = res[1]
});
}