angular - 等待 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
}
});
}
解决方案
您不能从异步函数(例如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();
}
顺便说一句,代码中有许多异常。
- 您正在将值分配给成员变量
this.totalPrice
。但在需要时不使用它。 - 将变量分配给函数,例如
let price = calculatePriceAPI();
指向函数。因为这里的输出是异步的,你不能从中返回同步数据。有关异步请求的信息,请参见此处。 - 成员函数应通过
this
关键字引用。它在let price = calculatePriceAPI();
. - 正如@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();
}
推荐阅读
- windows - 由于 Weblogic Server 警告消息导致的空间问题
- php - 除了 Sessions 之外,我还可以使用什么来将以下方法用作 API 方法?
- ruby-on-rails - 如何根据 Rails 5.2 中的 Time.zone(缩写与扩展名称)正确设置 time_zone_select 中的默认值?
- authorize.net - 是否可以多次进行部分退款?
- symfony4 - Service not found: even though it exists in the app's container
- django - Django ORM注释外键查询
- android - Manifest merger failed when adding CameraX gradle dependency
- python - 如何在 Gurobipy 中编写此约束?
- php - laravel-ffmpeg/php-ffmpeg 中的自定义过滤器?
- ruby-on-rails - 渲染一个 ActiveReccord:relationship 与特定的 cat 值