首页 > 解决方案 > 等待 API 完成,然后再转到方法中的下一步,而不将以下步骤放在订阅函数中

问题描述

如何等待 API 完成,然后使用干净的代码在 Angular 中执行下一步?我不想在订阅中放置未来的步骤。有没有办法先完成一个 API?

public overallMasterFunction(){
    executeMemberSetup();
    let price = calculatePriceAPI();  // Wait for this API line to complete, and conduct further steps
    let totalAmount = price * this.quantity;
    console.log('Sales Completed')
}

calculatePriceAPI(){
  this.customerSalesProxy.getPrice().subscribe(res => {
    if (res?.totalPrice) {
      this.totalPrice = res.totalPrice
    }
  });
}

标签: angulartypescriptangular8

解决方案


您不能从异步函数(例如let price = calculatePriceAPI();. 它违背了反应式编程。这种行为的一个重要原因是帮助解决诸如

如何等待 API 完成

. 你越早接受它,它就越容易使用。

也就是说,一种方法是从异步函数返回一个 observable。但请注意,您仍然需要订阅它才能使用该值。尝试以下

public overallMasterFunction(){
    executeMemberSetup();
    let totalAmount: any;
    this.calculatePriceAPI().subscribe(
      price => { totalAmount = price * this.quantity; }
    );
    console.log('Sales Completed');
}

calculatePriceAPI(){
  const result = new Subject<any>();

  this.customerSalesProxy.getPrice().subscribe(res => {
    if (res.totalPrice) {
      this.totalPrice = res.totalPrice;
      result.next(res.totalPrice);
    }
  });

  return result.asObservable();
}

顺便说一句,代码中有许多异常。

  1. 您正在将值分配给成员变量this.totalPrice。但在需要时不使用它。
  2. 将变量分配给函数,例如let price = calculatePriceAPI();指向函数。因为这里的输出是异步的,你不能从中返回同步数据。有关异步请求的信息,请参见此处
  3. 成员函数应通过this关键字引用。它在let price = calculatePriceAPI();.
  4. 正如@amakhrov 在评论中指出的那样,在这种特定情况下,该calculatePriceAPI()功能并没有做很多事情。主订阅可以直接在父函数中完成。
public overallMasterFunction(): Observable<any> {
    const result = new Subject<any>();
    let totalAmount: any;

    executeMemberSetup();
    this.customerSalesProxy.getPrice().subscribe(res => {
      if (res.totalPrice) {
        this.totalPrice = res.totalPrice;
        totalAmount = res.totalPrice * this.quantity;
        result.next(totalAmount);
      }
    });
    console.log('Sales Completed');

    return result.asObservable();
}

推荐阅读