3 回答

TA貢獻1827條經驗 獲得超9個贊
我知道你有 aserviceOne
和 a?serviceTwo
。并且您想serviceTwo
使用從 檢索到的數據進行調用serviceOne
。
使用 rxjs?switchMap您可以將一個可觀察值通過管道傳輸到另一個可觀察值中。
? 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
到傳遞數據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貢獻2065條經驗 獲得超14個贊
使用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貢獻1836條經驗 獲得超5個贊
有一些說法可以做到這一點:
場景#1
您的兩個服務 api 調用是獨立的,您只想調用一個,然后調用下一個
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")
});
場景#2
您的兩個調用相互依賴,因此您需要第一個調用的結果才能開始第二個調用
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,因為這樣做,第一次調用中的錯誤將意味著沒有結果發送到switchMap,并且永遠不會進行第二次調用。
添加回答
舉報