我需要订阅表单字段的值更改,并根据逻辑禁用它。此表单字段需要从API中的数据填充,该数据需要存储在数组中,并且需要设置为数组中的第一项。但是订阅会得到Uncaught RangeError: Maximum call stack size exceeded
,即使该值仅设置为1。这是代码:
currencyList : string[] = [];
ngOnInit() {
//form controls are initialized
this.handleCurrency();
}
handleCurrency(){
if(!this.formgroup.get('requestCurrency').value){
this.currencyService.fecthCurrencies().subscribe( (data) => {
this.currencyList = data;
this.defaultAndDisableCurrency();
}, () => {
//in case API call fails
this.currencyList.push("EUR");
this.defaultAndDisableCurrency();
});
}
//this.defaultAndDisableCurrency(); I would like to call the function here after API call is complete but this line gets executed without waiting for the call to complete
}
defaultAndDisableCurrency(){
let cur: any = this.formgroup.get('requestCurrency');
cur.valueChanges.subscribe((data)=>{
if(data === "EUR"){
cur.disable();
}
});
cur.setValue(this.currencyList[0]);
}
我没有测试它,但你能试试吗(我无法测试,因为我没有你的api,sry(
我使用异步等待函数来等待api响应
currencyList : string[] = [];
ngOnInit() {
//form controls are initialized
this.handleCurrency();
}
handleCurrency() {
if(!this.formgroup.get('requestCurrency').value){
this.currencyService.fecthCurrencies().subscribe( (data) => {
this.currencyList = data;
}, () => {
//in case API call fails
this.currencyList.push("EUR");
}, () => {
// Put it under the complete to avoid repeating code
this.defaultAndDisableCurrency();
});
} else {
// In the "else", because you'll call it if the controls already have value
this.defaultAndDisableCurrency();
}
}
async defaultAndDisableCurrency(): Promise<void>{
let cur: any = this.formgroup.get('requestCurrency');
await cur.valueChanges.subscribe((data)=>{
if(data === "EUR"){
cur.disable();
}
});
cur.setValue(this.currencyList[0]); // I don't understand what you're doing here
}
您需要等待API调用完成,这是对可观察订阅的第三次回调。
currencyList: string[] = [];
ngOnInit() {
this.handleCurrency();
}
handleCurrency() {
if (!this.formgroup.get('requestCurrency').value) {
this.currencyService.fecthCurrencies().subscribe(
(data) => {
this.currencyList = data;
this.defaultAndDisableCurrency();
},
(error) => {
this.currencyList.push('EUR');
this.defaultAndDisableCurrency();
},
(complete) => {
this.defaultAndDisableCurrency();
}
);
} else {
this.defaultAndDisableCurrency();
}
}
defaultAndDisableCurrency() {
let cur: any = this.formgroup.get('requestCurrency');
cur.valueChanges.subscribe((data) => {
if (data === 'EUR') {
cur.disable();
}
});
cur.setValue(this.currencyList[0]);
}