【问题标题】:Similar child component does not load from router outlet类似的子组件不会从路由器插座加载
【发布时间】:2016-07-28 18:55:22
【问题描述】:

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

我无法显示代码,但我可以尽力提供概述。父组件只有两个指令,即子组件。我在与父组件关联的 html 中路由到它们。加载父组件时,我订阅了一个文件项列表。在该订阅中,我有 JSON 响应,我将其解析为包含数据的对象。在这一点上,我有正确的数据。我可以控制台记录该数据。然后用 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()">

预览打字稿的代码 - PARENT

  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 子组件正在尝试加载文件项数组。

【问题讨论】:

  • 请分享一些代码
  • 请分享 preview-grid.component.html
  • 很难说。尝试转到您在屏幕截图中向我们展示的PriviewGridComponent.template.js.77,并显示代码
  • 我找到了可能的解决方案?我只是不确定如果它适用于一个组件而不适用于另一个组件,情况会如何。 stackoverflow.com/questions/37503322/…
  • service.getItems() 返回什么?我觉得这很混乱,因为 PARENT 还包含一个 getItems 方法。

标签: html http typescript angular angular2-routing


【解决方案1】:

如果你绑定到一个 observable,你需要使用 | async 管道

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

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 2016-08-02
    • 2020-10-03
    • 2017-04-29
    • 2018-05-29
    • 2021-03-13
    • 2023-03-06
    • 2017-07-02
    • 2017-02-28
    相关资源
    最近更新 更多