I have a problem that is driving me crazy. And I couldn't really find any answers anywhere so I'm finally posting here. Sorry for the german classes and variable names, but they shouldn't really matter.
So first, I want to retrieve JSON Objects from a REST Api and convert them to objects of my classes. To do that I have the following function:
async get(id, freizeit): Promise<Protokoll> {
let protokoll = new Protokoll();
(this.http.get(this.baseURL + "/" + id) as Observable<any>).subscribe(data => {
protokoll.id = data.id;
protokoll.name = data.name;
});
(this.http.get(this.pURL + id) as Observable<any>).subscribe(data => {
for (let element of data) {
let toInsert = new Frage();
Object.assign(toInsert, element);
protokoll.fragen.push(toInsert);
let answer = new Antwort();
answer.freizeit = freizeit;
answer.frage = toInsert.id;
protokoll.antworten.push(answer);
}
});
return protokoll;
}
Everything here works fine. If i console log length of protokoll.fragen, I always get the right length and can access the elements by protokoll.fragen[i]
.
So now, I want to get a Protokoll. I am doing that like the following:
async protokollZusammenstellen(freizeit: Freizeit) {
this.pzService.freizeit = freizeit;
let test: Protokoll;
await this.protokolleService.get(freizeit.protokoll, freizeit.id).then(protokoll => {
test = protokoll;
console.log("test");
});
console.log(test.fragen.length);
this.router.navigate(["/protokoll-zusammenstellen"]);
}
I already use async
and await
to ensure that there is no problem with async execution. console.log("test");
does print before console.log(fragen.length)
. But fragen.length
is 0 here. The same when I put the console log inside the .then()
function. But I need to access the fragen array here because I need to do further API requests.
If I use something like
for (let element of protokoll.fragen) {
...
}
then nothing ever happens. But if I console log the whole protokoll object, then everything is there. In Firefox the console even tells the length of protokoll.fragen
in a correct way.
What am I doing wrong? I really don't get it anymore.