【问题标题】:How make component finish loading first before html in angular如何让组件在 html 之前完成加载
【发布时间】:2021-11-02 22:39:11
【问题描述】:

所以我有这个带有图表的仪表板页面和一些带有数据的卡片。检索数据的函数在 ngOnInit() 中,但问题是当页面加载时,数据显示为 0。如果我单击图表或其他内容,则数据会加载。无论如何可以直接获取页面加载时的数据?我尝试设置一个布尔值,它将在 nginit 结束时变为真,但它仍然不起作用。

<div *ngIf="isLoaded">
Page here
</div>

这是 ts 文件。

export class DashboardAgentComponent implements OnInit {

totalAssigned=0;
totalAssignedHigh=0;
totalAssignedMed=0;
totalAssignedLow=0;
totalPending=0;
totalPendingHigh=0;
totalPendingMed=0;
totalPendingLow=0;
totalUnassigned=0;
public allTags$ = new BehaviorSubject<Tag[]>([]);
public threeDaysPending = 0;
public sevenDaysPending =0;
public fourteenDaysPending = 0;

public threeDaysAssigned = 0;
public sevenDaysAssigned =0;
public fourteenDaysAssigned = 0;
public isLoaded : boolean =  false;


ngOnInit() :void{
this.getTotalAssigned();

}

public trackByFn = (i: number, tag: Tag) => tag.id;



getTotalAssigned()
{
  this.mailboxTags.getTotalPending().subscribe((tags: Tag[]) => {
    console.log(tags);
    // this.allTags$.next(tags);
    for (let index = 0; index < tags.length; index++) {
      if(tags[index].name == 'pending' && tags[index].type=='view')
      {
        this.totalPending = tags[index].tickets_count;
      }

      else if(tags[index].name == 'unassigned')
      {
        this.totalUnassigned = tags[index].tickets_count;
      }

      else if(tags[index].name == 'assigned'&& tags[index].type=='view')
      {
        this.totalAssigned = tags[index].tickets_count;
      }
    }
 });
this.getPendingTickets();

}

getPendingTickets()
{
this.mailboxTags.getPendingHighTickets().subscribe((res: any) => {
  let currentDate: any = new Date();
  
    for (let index = 0; index < res.pagination.data.length; index++) {
      if(res.pagination.data[index].status=="pending")
      {
        let createdDate: any = new Date(res.pagination.data[index].created_at);
        var diffDays:any = Math.floor((currentDate - createdDate) / (1000 * 60 * 60 * 24));

        if(diffDays>3 && diffDays<7)
        {
          this.threeDaysPending++;
        }

        else if(diffDays>=7 && diffDays<14)
        {
          this.sevenDaysPending++;
        }

        else if(diffDays>=14)
        {
          this.fourteenDaysPending++;
        }
      }
    }

    for (let index = 0; index < res.pagination.data.length; index++) {
      if(res.pagination.data[index].status=="assigned")
      {
        let createdDate: any = new Date(res.pagination.data[index].created_at);
        var diffDays:any = Math.floor((currentDate - createdDate) / (1000 * 60 * 60 * 24));

        if(diffDays>3 && diffDays<7)
        {
          this.threeDaysAssigned++;
        }

        else if(diffDays>=7 && diffDays<14)
        {
          this.sevenDaysAssigned++;
        }

        else if(diffDays>=14)
        {
          this.fourteenDaysAssigned++;
        }
      }
    }
   
    this.isLoaded =  true;
    
    
  
  
 });
 }


constructor(private breakpointObserver: BreakpointObserver, public mailboxTags: MailboxTagsService) {}

}

基本上所有将使用的数据都在 ngOnInit 函数中。

这是html。它不完整,但其他类似。

<div class="grid-container"  *ngIf="isLoaded   == true">
<h1 class="mat-h1">Dashboard</h1>
<mat-grid-list cols="3" rowHeight="550px" colWidth="100px">
  <mat-grid-tile   class="grid-tile"  [colspan]="1" [rowspan]="1">
    <ng-container >
      <mat-card class="dashboard-card" >
        <mat-card-header>
          <mat-card-title>
            Unassigned
            <button mat-icon-button class="more-button" 
        [matMenuTriggerFor]="menu" aria-label="Toggle menu">
              <mat-icon>more_vert</mat-icon>
            </button>
            <mat-menu #menu="matMenu" xPosition="before">
              <button mat-menu-item>Expand</button>
              <button mat-menu-item>Remove</button>
            </mat-menu>
          </mat-card-title>
        </mat-card-header>
        <mat-card-content class="dashboard-card-content">
          <div>{{totalUnassigned}}</div>
        </mat-card-content>
      </mat-card>
    </ng-container>
   </mat-grid-tile>
   </mat-grid-list>
   </div>

因此,totalUnassigned 为 0,除非我打开我的 matmenu 然后数据会更新。

【问题讨论】:

  • 如果数据是异步加载的,那么您需要等待调用完成才能将isLoaded设置为true。您还可以查看 Angular Resolvers,它确保为调用 ngOnInit 加载数据。
  • @andyiscoding 检查我的更新答案
  • 路由解析器对于这种情况来说是一个完美的功能。 angular.io/api/router/Resolve
  • @surajrawat 谢谢,我去看看
  • @Nathan 也感谢您推荐 Angular Resolvers

标签: angular typescript


【解决方案1】:

我尝试设置一个布尔值,它将在 nginit 结束时变为真 但是还是不行。

您不能将isLoaded=true 设置在ngOnInit() 的末尾。这并不能确保所有数据都已成功加载。

我很确定您错过了异步编程的基础知识,您必须在 get 调用的回调函数中进行任何更改。

ngOnInit() {
   ...
   ..asynchronousCall...
   ...

  this.isLoaded=true
} 

上述情况将不起作用。

  ngOnInit() {
       ...
       ..asynchronousCall.subscribe( e => {
          this.isLoaded=true
        });
       ...
    } 

上述情况将起作用,因为当异步回调函数 get 执行并且已从后端成功获取数据时,布尔值将被更新

编辑: 在您发布所有代码后,我对您的错误的第一次估计是正确的。

您可以通过以下方式解决此问题 在getTotalAssigned() 的订阅中移动方法调用this.getPendingTickets();。这样,只有在提取了 totalAsigned 票证后,才会提取待处理票证。

还将this.isLoaded = true; 移动到getPendingTickets() 的订阅中

像这样重构代码后,您将实现 this.isLoaded 仅在获取 TotalAsigned 并获取 pendingTickets 时才变为真。

【讨论】:

  • 更好的办法是将 2 个 observables 以某种方式与 forkJoin 组合在一起,并在组合结果可用后更改 isLoaded
  • 感谢您的帮助,我确实像您说的那样将获取待处理的票证和设置加载到 get totalassigned 中,但 html 仍然显示在获取数据之前的初始值,即 0。
  • @andyiscoding 那么相关的html必须在&lt;div *ngIf="isLoaded"&gt;之外
  • 所有的 html 都已经在 div ngIf 中了。唯一外部是无关紧要的材料导航栏。我测试了它,如果我没有设置isLoaded = true,页面是空白的。如果我设置它,页面会加载但初始值为 0。
  • @andyiscoding 使用您当前的代码更新问题以查看错误在哪里
【解决方案2】:

我已经使用 Angular Resolvers 解决了这个问题。由于某种原因,单独的 ngIf 方法不起作用。这是我更新的代码:

  constructor(private breakpointObserver: BreakpointObserver, public mailboxTags: MailboxTagsService, private _route: ActivatedRoute) {
 this.respond = this._route.snapshot.data['tickets'];
 this.tag =this._route.snapshot.data['tag'];
 this.userID = this._route.snapshot.data['id'];

let currentDate: any = new Date();
  
    for (let index = 0; index < this.respond.pagination.data.length; index++) {
      if(this.respond.pagination.data[index].assigned_to == this.userID)
      {
        if(this.respond.pagination.data[index].status=="pending")
      {
        let createdDate: any = new Date(this.respond.pagination.data[index].created_at);
        var diffDays:any = Math.floor((currentDate - createdDate) / (1000 * 60 * 60 * 24));

        if(diffDays>3 && diffDays<7)
        {
          this.threeDaysPending++;
        }

        else if(diffDays>=7 && diffDays<14)
        {
          this.sevenDaysPending++;
        }

        else if(diffDays>=14)
        {
          this.fourteenDaysPending++;
        }
      }
      }
      
    }

    for (let index = 0; index < this.respond.pagination.data.length; index++) {
      if(this.respond.pagination.data[index].assigned_to == this.userID){
        if(this.respond.pagination.data[index].status=="assigned")
      {
        let createdDate: any = new Date(this.respond.pagination.data[index].created_at);
        var diffDays:any = Math.floor((currentDate - createdDate) / (1000 * 60 * 60 * 24));

        if(diffDays>3 && diffDays<7)
        {
          this.threeDaysAssigned++;
        }

        else if(diffDays>=7 && diffDays<14)
        {
          this.sevenDaysAssigned++;
        }

        else if(diffDays>=14)
        {
          this.fourteenDaysAssigned++;
        }
      }
      }
    }  

    for (let index = 0; index < this.tag.length; index++) {
      if(this.tag[index].name == 'pending' && this.tag[index].type=='view')
      {
        this.totalPending = this.tag[index].tickets_count;
      }

      else if(this.tag[index].name == 'unassigned')
      {
        this.totalUnassigned = this.tag[index].tickets_count;
      }

      else if(this.tag[index].name == 'assigned'&& this.tag[index].type=='view')
      {
        this.totalAssigned = this.tag[index].tickets_count;
      }
    }
    this.isLoaded=true;
   }

【讨论】:

  • 您不需要解析器。您的问题是您仍然有this.getPendingTickets(); 外部订阅。应该是 }); this.getPendingTickets(); .. 时应该是 this.getPendingTickets(); }); 订阅应该在调用 this.getPendingTickets() 后关闭 })
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多