I have the following method, which sends data towards my backend and then gets data back regarding the mutations that happened (how many actual new rows were added to the database). However if I use my method like this, my response will be holding the value that I want.. my this.stats won't however. Probably happening because the value is assigned after I've returned the variable already.
uploadfile.service.ts
PostCourses(objArray : object[]) : CoursesAddedStats {
this.http.post<CoursesAddedStats>('https://localhost:7125/api/courses', objArray, this.httpOptions)
.subscribe((response : CoursesAddedStats) => {
this.stats = response;
});
return this.stats;
}
add-course-component.ts
readFile = (file: any) => {
const fileReader : FileReader = new FileReader();
fileReader.onloadend = (ev) => {
const data = fileReader.result;
var txtData = data!.toString();
this.values = this.uploadFileService.upload(txtData);
this.stats = this.uploadFileService.PostCourses(this.values);
}
fileReader.readAsText(file);
if (this.stats.courseInstancesAdded) {
this.message = `There have been ${ this.stats.coursesAdded } new courses and ${ this.stats.courseInstancesAdded} new course instances added`
this.showMessage = true;
}
}
Where I wanna use this: add-course-component.html
<input type="file" (change)="getFile($event)"/>
<div>
<p
*ngIf="showMessage"
>
{{ message }}</p>
</div>
courseaddedstats.ts
export class CoursesAddedStats {
coursesAdded: number = 0;
courseInstancesAdded: number = 0;
}
Anyone has a suggestion on how to fix it, so my return this.stats actually does hold the response value when I return it?
You can convert it into a promise and simply await it like this
async PostCourses(objArray : object[]) : Promise<CoursesAddedStats | nulll> {
this.stats = await firstValueFrom(this.http.post<CoursesAddedStats>('https://localhost:7125/api/courses', objArray, this.httpOptions));
return !!this.stats ? this.stats : null;
}
The reason that you will always have to deal with Promise or Observable is that the API call is asynchronous and function calls are synchronous and you cannot hold the Js thread until the call is resolved and even if you can, the whole UI would be blocked for the time call is being resolved
CONCLUSION: