以下是特定場景的代碼流。首先,一個 POST 呼叫。此 POST 呼叫更新資料庫中表的列。然后,訂閱它,并進行 GET 呼叫。使用此 GET 呼叫的結果,我更新了頁面上的引數。完成這兩個呼叫后,我應該進行 PUT 呼叫以更新一些變數(未從先前的 GET 呼叫中檢索),然后發出一個事件。下面是代碼:
save({ job, status }) {
this.apiService.serviceMethod(job, status);
console.log('calls after publishTaskAction');
this.apiService.updatePutMethod(job).subscribe(() => {
console.log('after updateTask');
});
this.notify.emit('saved!');
}
ApiService 方法:
serviceMethod(job: Model, status: string) {
if (status) {
let observ = of() as Observable<void>;
if (status === 'Publish') {
observ = this.firstPostMethod(task);
}
if (status === 'UnPublish') {
observ = this.firstPostMethod(task);
}
console.log('calls before observ');
observ.subscribe(() => {
console.log('inside observ');
this.firstGETCall(task).subscribe();
console.log('after observ');
});
}
}
我想要實作的是 serviceMethod 應該完成執行(完成 Post 和 Get 呼叫),然后回傳呼叫者方法并執行 updatePutMethod。發生的事情是執行回傳給呼叫者并執行 updatePutMethod 然后呼叫 observ.subscribe。因此,在后端,結果并不如預期。這是執行 console.logs 的順序:
calls before observ
calls after publishTaskAction
before updateTask http call
inside observ
after observ
tafter updateTask
我遵循了這個解決方案:訂閱在下面的代碼執行后被呼叫?. 并更新我的代碼如下:
save({ job, status }) {
this.apiService. serviceMethod(job, status).subscribe(
(data) => {
this.apiService.firstPostMethod(job).subscribe(
(data) => {
this.taskApiService.updateTask(task).subscribe();
}
);
this.notify.emit('saved!');
});
}
但這是錯誤的。此外,我從幾個來源中了解到不應從另一個訂閱塊呼叫訂閱。所以請幫忙提出任何建議。
uj5u.com熱心網友回復:
這就是 RxJS 管道的方便之處。在呼叫最后一個訂閱之前,您可以一個接一個地繼續觀察。
重申您想要的功能:在您的 UI 組件中,您按下保存任務和狀態的按鈕。您想要 POST 作業以將任務保存到資料庫,然后執行 GET 以檢索其他資料。
請注意,在繼續之前,如果您正在 POST 以保存 TASK,并且接下來的 GET 是為了檢索更新的 TASK,則您始終可以從 POST 呼叫中回傳更新的 TASK。
獲得更新的資料后,您將更新 UI,然后更新您需要使用 PUT 呼叫更新的附加變數。
最后,一旦所有變數都被 POST、GET、PUT 和 UI 更新后,您希望將所有操作發送到父組件。
我的建議。
save(job: Model, status: string) {
console.log('Starting apiService.serviceMethod');
this.apiService.serviceMethod(job, status).pipe(
switchMap((job: Model) => {
if (job) {
// Some update of job is require here since the GET call doesn't know
// whereas the UI does.
// Modify job variable here.
console.log('Starting PUT call');
return this.apiService.updatePutMethod(job);
} else {
console.log('Skipping PUT call');
return of(null);
}
})
).subscribe(() => {
console.log("Ready to emit");
this.notify.emit('Saved!');
});
}
import { of } from 'rxjs';
serviceMethod(job: Model, status: string): Observable<Model> {
if (status && (status === 'Publish' || status === 'UnPublish')) {
console.log('Staring POST call');
return this.firstPostMethod(task).pipe(
switchMap((task) => {
console.log('Starting GET call');
return this.firstGETCall(task);
})
);
} else {
// either status is null/empty or does not equal either of the strings.
return of(null);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404685.html
標籤:
