3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
我知道你有 aserviceOne
和 a?serviceTwo
。并且您想serviceTwo
使用從 檢索到的數(shù)據(jù)進(jìn)行調(diào)用serviceOne
。
使用 rxjs?switchMap您可以將一個(gè)可觀察值通過(guò)管道傳輸?shù)搅硪粋€(gè)可觀察值中。
? handler(): void {
? ? ? ? this.serviceOne
? ? ? ? ? ? .createDirectory(this.path)
? ? ? ? ? ? .pipe(
? ? ? ? ? ? ? ? switchMap(serviceOneResult => {
? ? ? ? ? ? ? ? ? ? // transform data as you wish
? ? ? ? ? ? ? ? ? ? return this.serviceTwo.methodCall(serviceOneResult);
? ? ? ? ? ? ? ? })
? ? ? ? ? ? )
? ? ? ? ? ? .subscribe({
? ? ? ? ? ? ? ? next: serviceTwoResult => {
? ? ? ? ? ? ? ? ? ? // here we have the data returned by serviceTwo
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? error: err => {},
? ? ? ? ? ? });
? ? }
如果您不需要從serviceOne
到傳遞數(shù)據(jù)serviceTwo
,但需要它們一起完成,則可以使用 rxjs?forkJoin。
? handler(): void {
? ? ? ? forkJoin([
? ? ? ? ? ? this.serviceOne.createDirectory(this.path),?
? ? ? ? ? ? this.serviceTwo.methodCall()
? ? ? ? ])
? ? ? ? .subscribe({
? ? ? ? ? ? next: ([serviceOneResult, serviceTwoResult]) => {
? ? ? ? ? ? ? ? // here we have data returned by both services
? ? ? ? ? ? },
? ? ? ? ? ? error: err => {},
? ? ? ? });
? ? }

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
使用aysncandawait你可以這樣做:
async handler(): void {
await this.serviceNAme
.createDirectory(this.path)
.pipe(
finalize(() => {
this.someProperty = false;
})
)
.subscribe(
(data) => console.log(data),
(error) => console.error(error.message)
);
// Do second api call
}

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
有一些說(shuō)法可以做到這一點(diǎn):
場(chǎng)景#1
您的兩個(gè)服務(wù) api 調(diào)用是獨(dú)立的,您只想調(diào)用一個(gè),然后調(diào)用下一個(gè)
const serviceCall1 = this.serviceName.createDirectory(this.path);
const serviceCall2 = this.serviceName.createDirectory(this.otherPath);
concat(serviceCall1 , serviceCall2).subscribe({
next: console.log,
error: err => console.error(err.message),
complete: () => console.log("service call 1&2 complete")
});
場(chǎng)景#2
您的兩個(gè)調(diào)用相互依賴(lài),因此您需要第一個(gè)調(diào)用的結(jié)果才能開(kāi)始第二個(gè)調(diào)用
this.serviceName.getDirectoryRoot().pipe(
switchMap(root => this.serviceName.createDirectoryInRoot(root, this.path))
).subscribe({
next: console.log,
error: err => console.error(err.message),
complete: () => console.log("service call 1 used to create service call 2, which is complete")
});
您將需要方案 # 2,因?yàn)檫@樣做,第一次調(diào)用中的錯(cuò)誤將意味著沒(méi)有結(jié)果發(fā)送到switchMap,并且永遠(yuǎn)不會(huì)進(jìn)行第二次調(diào)用。
添加回答
舉報(bào)