首页 > 解决方案 > 在一个角度函数中分别调用两个订阅而不混合它们

问题描述

我试图在一个角度函数中调用 2 个订阅请求,不幸的是只完成了第一个请求

debugger;
            this.tableService.UpdateTableStatus(tableCode).subscribe(result => {
             this.statusUpdatedSuccessfully = result;
             if (this.statusUpdatedSuccessfully === true) {
               this.flag = true;
               alert('statusUpdatedSuccessfully');
             }
            });
   
           this.newOrder.employeeCode = this.employee.globalPassword;
           this.newOrder.orderTime = new Date();
           this.newOrder.restaurantTableCode = tableCode;
           this.newOrder.totalpayment = 0;
           this.orderService.addNewOrder(this.newOrder).subscribe(result => {
             // tslint:disable-next-line: no-debugger
             debugger;
             this.orderCode = result;
             this.tableToAdd.orderCode = this.orderCode;
             this.tableToAdd.tableCode = tableCode;
             this.orderService.listBusyTable.push(this.tableToAdd);
            });
           this.router.navigate(['/orders-in-process', tableCode]);
         }

标签: angularapipostupdates

解决方案


我敢打赌这是因为你在它有机会进入第二个之前就已经离开了subscribe

asubscribe中的Asubscribe是反模式,因此使用 aswitchMap切换到新的 observable。

import { switchMap } from 'rxjs/operators';
....
debugger;
            this.tableService.UpdateTableStatus(tableCode).pipe(
              switchMap(result => {
                 this.statusUpdatedSuccessfully = result;
                 if (this.statusUpdatedSuccessfully === true) {
                    this.flag = true;
                   alert('statusUpdatedSuccessfully');
                }
               });
    
               this.newOrder.employeeCode = this.employee.globalPassword;
               this.newOrder.orderTime = new Date();
               this.newOrder.restaurantTableCode = tableCode;
               this.newOrder.totalpayment = 0;
               return this.orderService.addNewOrder(this.newOrder);
              })
            ).subscribe(result => {
             this.orderCode = result;
             this.tableToAdd.orderCode = this.orderCode;
             this.tableToAdd.tableCode = tableCode;
             this.orderService.listBusyTable.push(this.tableToAdd);
             // once the API call of addNewOrder is done and subsribed to here,
             // navigate away
             this.router.navigate(['/orders-in-process', tableCode]);
           });
           
         }

如果要保留inside ,则必须将行移到第二个订阅回调的subscribe内部。subscriberouter.navigate


推荐阅读