0

我有一个组件,它对调用 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 检查)。唯一的问题是页面在数据加载完成之前呈现。

有任何想法吗?

提前致谢!

4

2 回答 2

2

您是否尝试过使用解析?

创建一个解析器名称为 assignments-details.resolver.ts

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {MeService} from '../services/me.service';

@Injectable()
export class AssignmentsDetailsResolver implements Resolve<any> {

  constructor(api: MeService){}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
   return this.api.getAssignments();
  }

}

然后在你的路线配置上这样做

{
  path: 'your_path',
  component: NewrequestComponent,
  resolve: { AssignmentsDetails: AssignmentsDetailsResolver }
}

然后在您的 NewrequestComponent 上确保您导入 ActivatedRoute

import { ActivatedRoute } from '@angular/router'

在你的承包商中这样称呼它

 constructor(private meService: MeService,
              private authService: AuthService,
              private assignmentService: AssignmentService,
              private router: Router,
              public nav: NavbarService,
              private activateRoute: ActivatedRoute) {

   this.activateRoute.data.subscribe((response) => {
       //to get the response
       console.log(response.AssignmentsDetails);
     });
  }

并确保在模块的提供程序属性中注册“AssignmentsDetailsResolver”。

希望这对您有所帮助。

于 2018-04-10T08:52:17.777 回答
0

是 由于服务调用是异步的,调用订阅时数据不会立即到达。

但是在您的代码中,一旦数据到达,您就没有将 ready 变量设置为 true。所以你在页面上看不到任何数据。获取数据后将其设置为 true

this.me = data;
this.ready =true;

或通过安全导航操作员处理。

于 2018-04-10T08:27:00.993 回答