我有一个角度为6的服务,其中包含方法“ saveEntity”,该方法可以保存执行多个请求的实体。我需要执行以下操作: 该方法调用一个URL->一旦获得响应,我也需要调用另一个URL->一旦获得该第二响应,我需要将最终数据返回给Component。
所以在我的组件中,我将拥有
service.saveEntity(entity).subscribe();
进入服务后,我需要做什么?
答案 0 :(得分:0)
@Injectable({providedIn: 'root'})
export class MultiSaveService {
constructor(private http: HttpClient) {
}
saveMultipleInParallel(): Observable<[string, number]> {
return forkJoin([
this.http.post<string>('my-url', {
stringData: 'stringData'
}),
this.http.post<number>('my-url', {
numberData: 1
})
])
}
saveMultipleOneByOne(): Observable<[string, number]> {
return this.http.post<string>('url', {stringData: 'stringData'}).pipe(
withLatestFrom(this.http.post<number>('url', {numberData: 5}))
)
}
}
您的订阅应如下
this.multiSaveService.saveMultipleInParallel()
.subscribe(([firstCallResult, secondCallResult]) => {
console.log(firstCallResult);
console.log(secondCallResult);
})
答案 1 :(得分:0)
service.ts
firstOperation() {
return http.get('url1')
}
secondOperation() {
return http.get('url2')
}
第二项服务在第一项服务之后触发:一次可以使用mergeMap
或concatMap
bothOperations1() {
service.firstOperation().pipe(
mergeMap(data1 => {
// do something with data1
return service.secondOperation()
})
)
}
但是,如果两种服务都要并行调用,则可以使用forkJoin
bothOperations2() {
return forkjoin([service.firstOperation(), service.secondOperation()])
}
component.ts
saveEntity1() {
service.BothOperation1().subscribe(data => {
// do whatever is needed with the data2
})
}
saveEntity2() {
service.bothOperation2().subscribe(([data1, data2]) => {
// do whatever is needed with data1 and data2
})
}