【发布时间】:2021-04-29 13:44:47
【问题描述】:
我有一个 Angular 组件,它在 init 中执行 2 个函数,其中一个为数组充电,第二个获取数组的值并执行服务。
问题是第二个函数在第一个函数之前执行,所以数组不充电,第二个函数返回错误。
这是代码:
import { fromEvent, Subscription } from 'rxjs';
ngOnInit(): void {
this.getProducts();
this.getLoans();
}
getProducts() {
this.clientService.getClientProducts(this.clientId).subscribe(
(res) => {
if (res.success) {
this.products = res.data;
console.log('Obtiene productos');
console.log(this.products);
}
}
);
}
getLoans() {
console.log('Obtiene loans');
console.log(this.products);
this.products.forEach((element) => {
if (element.id == '4') {
this.clientService.getClientLoan(this.clientId).subscribe(
(res) => {
if (res.success) {
this.loans.push(res.data);
} else {
this.hasErrorOnLoans = true;
}
},
);
}
});
}
还有控制台日志,能不能看到之前第一个函数执行的日志:
对不起我的英语!谢谢。
【问题讨论】:
-
我建议当第一个方法在订阅回调中收到响应时调用第二个方法
-
需要在getProducts订阅中调用getLoans,对异步编程稍作研究。
标签: angular typescript rxjs