html - 类似的子组件不会从路由器导出加载

标签 html http typescript angular angular2-routing

我正在创建一个文件上传前端,并且有文件的 GridView 和文件的 ListView 。它们都是来自父 Preview 组件的子组件。对于 GridView 和 ListView ,类型脚本文件几乎是完全相同的东西。当用户在 url 中加载带有行的页面时,页面将加载并且一切正常。当页面加载 url 中的网格时,页面将崩溃。这是错误:enter image description here

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

同样,这适用于一个子组件,但不适用于另一个。在网格组件中,上面发布的错误在加载时显示。它说属性项未定义。我的猜测是,对于网格组件,试图到达“项目”数组的 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()">

预览 typescript 代码 - 父

  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 请求之前,网格子组件正在尝试加载文件项数组。

最佳答案

如果你绑定(bind)到一个observable,你需要使用|异步管道

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

关于html - 类似的子组件不会从路由器导出加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644602/

相关文章:

html - 在 div 中并排 Bootstrap 图像和文本

http - 302 和 307 重定向有什么区别?

typescript - 如何使用 Yup 验证相互依赖的数字字段?

javascript - request.end() 之后重新发送响应

angular - 如何配置 Angular 5 以支持模块别名?

angular - 将 FormGroup 放入类中的最佳方法

html - 输入顶部边框在 windows chrome 中消失

javascript - react redux 打印 Prop 的方式

javascript - 在 android 浏览器中播放 html5 音频

python - urllib2 HTTPError : HTTP Error 414: Request-URI Too Large