我有一个组件,它对调用 api 的服务执行一些调用。组件在这些调用完成之前呈现,导致页面为空。
这是来自组件的代码:
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));
});
}
}
这是页面中的代码:
<app-navbar-component></app-navbar-component>
<div *ngIf="ready">
<div *ngFor="let request of requests">
<p class="lead">{{request.user}}</p>
</div>
</div>
这是我的服务中的功能:
getAssignments() {
return this.http.get(this.BASE_API_URL + '/assignments').catch(this.onError);
}
我没有错误。请求已加载(通过 console.log 检查)。唯一的问题是页面在数据加载完成之前呈现。
有任何想法吗?
提前致谢!