I have something like this
getFieldsRemote(){
let fields: FormfieldBase<any>[] = [];
this.http.get('http://localhost:8080/api/getFields').subscribe(
data =>{
// code to push objects from data to fields variable declared above
}
}
)
return fields;
}
Now the problem I'm facing is that whenever I call this getFieldsRemote()
method from my other components I get a blank array. I understand this is happening because subscribe method is asynchronous therefore it is working in the background and the control reaches the return statement before code section inside subscribe is executed. However I need this function to somehow return the data when the subscribe method has completed. Subscribing to the data in the component side is not an option. Please tell me what's the solution here.
If you don't want to have to worry about subscriptions you can simply turn into a promise and use async/await
async getFieldsRemote(){
let fields: FormfieldBase<any>[] = [];
const data = await this.http.get('http://localhost:8080/api/getFields').toPromise()
// do what you want with the data
return fields
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments