My component is making calls to a service that in turn calls an API. However, the component renders before these calls are completed, resulting in an empty page.
Here's the code snippet from the component:
import {Component, OnInit, OnDestroy} from '@angular/core';
import {AuthService} from '../services/auth.service';
import {AssignmentService} from '../services/assignment.service';
import {Assignment} from '../models/Assignment';
import {Request} from '../models/Request';
import {MeService} from '../services/me.service';
import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';
import {Router} from '@angular/router';
import {NavbarService} from '../services/navbar.service';
@Component({
selector: 'app-newrequest',
templateUrl: './newrequest.component.html',
providers: [AssignmentService]
})
export class NewrequestComponent implements OnInit {
me: MicrosoftGraph.User;
assignments: Assignment[];
requests: Request[] = [];
ready = false;
constructor(private meService: MeService,
private authService: AuthService,
private assignmentService: AssignmentService,
private router: Router,
public nav: NavbarService) {
}
ngOnInit() {
this.nav.show();
this.nav.element = 'newrequests';
if (localStorage.getItem('loggedin') === 'yes') {
this.meService.getMe().subscribe(data => {
this.me = data;
},
error => {
console.log(error);
},
() => this.assignmentService.getAssignments().subscribe(data => {
this.assignments = data;
},
error => {
console.log(error);
},
() => {
this.setRequests();
}));
} else {
this.router.navigate(['']);
}
}
onLogout() {
this.authService.logout();
}
onLogin() {
this.authService.login();
}
private setRequests() {
this.assignments.forEach(item => {
if (this.me.mail.toLowerCase() === item.lecturer.toLowerCase()) {
this.parseRequests(item.request, item.name);
}
});
this.ready = true;
}
private parseRequests(toSplit, name) {
const split = toSplit.split(',');
split.forEach(item => {
this.requests.push(new Request(item, name));
});
}
}
This is the code snippet from the page:
<app-navbar-component></app-navbar-component>
<div *ngIf="ready">
<div *ngFor="let request of requests">
<p class="lead">{{request.user}}</p>
</div>
</div>
This is the function within my service:
getAssignments() {
return this.http.get(this.BASE_API_URL + '/assignments').catch(this.onError);
}
I am not receiving any errors. The requests are being loaded successfully (confirmed via console.log). The only issue is that the page loads before the data finishes loading.
Any suggestions or ideas would be greatly appreciated!
Thank you in advance!