I’m calling createOtherKind() function and trying to use the value of this.listKinds. My problem is that isKindOtherCreated is not waiting this.getKinds() to finish and this.listKinds is undefined.
How can i do it?
Code:
getKinds(): void {
this.detailsService.getKinds().subscribe(async response =>{
this.listKinds = await response.body;
})
}
async createOtherKind() {
await this.getKinds();
const isKindOtherCreated = this.listKinds.find(kind => kind.name === "Other");
if(!isKindOtherCreated) {
this.createdKind.name = "Other";
this.createKind();
}
}
>Solution :
You use subscribe here, so I guess this.detailsService.getKinds() returns an observable. You can make things with it then return it to be able to subscribe something else in another part of your code. like:
getKinds(): Observable<any> {
let myObs = this.detailsService.getKinds(); //Getting your observable
//Reading result
myObs.subscribe(response => {
this.listKinds = response.body;
});
//Returning it to use it somewhere else
return myObs;
}
createOtherKind() {
//Make request and subscribe to observable
this.getKinds().subscribe( res => {
const isKindOtherCreated = this.listKinds.find(kind => kind.name === "Other");
if(!isKindOtherCreated) {
this.createdKind.name = "Other";
this.createKind();
}
}
}