类似的子组件不会从路由器插座加载

时间:2016-07-28 18:55:23

标签: html http typescript angular angular2-routing

我正在创建一个文件上传前端,并有文件的网格视图和文件的列表视图。它们都是父预览组件的子组件。对于网格视图和列表视图,类型脚本文件几乎完全相同。当用户在URL中加载包含行的页面时,页面将加载并且一切正常。当页面加载网址在网址中时,页面将崩溃。这是错误:enter image description here

我无法显示代码,但我可以尽力概述。父组件只有两个指令,即子组件。我在与父组件关联的html中路由到它们。加载父组件时,我订阅了一个文件项列表。在该订阅中,我有JSON响应,我将其解析为包含数据的Object。此时,我有正确的数据。我可以控制日志数据。然后,我拥有的对象将填充JSON数据。

同样,这适用于一个子组件,但不适用于另一个子组件。在网格组件中,上面发布的错误在加载时显示。它说属性项是未定义的。我的猜测是,对于网格组件,在订阅完成加载到父组件之前,加载试图到达“items”数组的html。如果这是问题,我该如何处理?

此外,当我将调试器放在子组件html调用的getItems方法中时,上面的错误出现在调试器启动之前。

网格html代码 - CHILD 1

<div *ngIf="isEmpty()" class="full-height">
  <app-upload></app-upload>
</div>
<div class="grid-container">
  <div class="container-width" *ngFor="let file of service.getItems()">
    <div class="preview-ico-container">
      <img *ngIf="needsLabelIcon(file)" class="img-responsive label-icon-size" src="app/resources/img/ico/{{file.ext}}.ico" alt="">
      <img *ngIf="file.type=='image'" class="img-responsive preview-ico-size" alt="Responsive image" src='{{ file.dataUri }}'>
      <img *ngIf="file.type!='image'" class="img-responsive preview-ico-only" alt="Responsive image" src="app/resources/img/ico/{{file.ext}}.ico">
    </div>
    <div class="preview-img-name-container">
      {{ file.fileName }}
    </div>
  </div>
</div>

行html代码 - CHILD 2

  <tr class="table-content" *ngFor="let file of service.getItems()">

预览打字稿代码 - 父母

  ngOnInit() {
    this.getItems();
  }

  getItems() {
    this.service.Get().subscribe((data) => {
      debugger  //TESTING
      console.log(data);  //TESTING
      // SetModelView takes a json response and parses it into a an object I
      //   made. This is also where the items array is set, which
      //   service.getItems() looks at in both the child components
      this.service.setModelView(data);
      this.isNext_Prev();
    });
  }

  isNext_Prev() {
    if (this.service.modelView && this.service.modelView._links.next) {
      this.nextDisplay = "inline-block";
    } else {
      this.nextDisplay = "none";
    }
    if (this.service.modelView && this.service.modelView._links.previous) {
      this.prevDisplay = "inline-block";
    } else {
      this.prevDisplay = "none";
    }
  }

当我将调试器放在我的服务中与我的API通信的Get请求方法时,错误已经存在。因此,在第一次http请求之前,grid子组件正在尝试加载文件项数组。

1 个答案:

答案 0 :(得分:0)

如果绑定到observable,则需要使用| async管道

<div class="container-width" *ngFor="let file of service.getItems() | async">