首页 > 解决方案 > Angular ngFor 绑定错误。为什么我会收到错误消息?

问题描述

我有一个名为 DOCUMENT 的主要组件。该文档采用 URL 段并从我的数据库中获取关联对象的数组。然后,在 DOCUMENT VIEW 组件中使用@Output() documents = new EventEmitter()和,然后使用. 整个事情都有效并显示了元素,但我不断收到错误消息@Input()*ngFor

错误:找不到“object”类型的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays。

我难住了。由于某种原因,感觉就像是打字稿类型错误。我实际上 console.log 初始数据库返回,实际上,它是一个对象数组。所以,不确定这个错误来自哪里

----------TS----------

import { Component, OnInit, Output, EventEmitter } from "@angular/core";
import { DocumentService } from "src/app/services/document.service";
import { ActivatedRoute, Router, NavigationEnd } from "@angular/router";

@Component({
  selector: "app-documents",
  templateUrl: "./documents.component.html",
  styleUrls: ["./documents.component.css"]
})
export class DocumentsComponent implements OnInit {
  @Output() documents = new EventEmitter();
  department;
  navigationSubscription;

  constructor(
    private _documentService: DocumentService,
    private _route: ActivatedRoute,
    private _router: Router
  ) {
    // subscribe to the router events - storing the subscription so
    // we can unsubscribe later.
    this.navigationSubscription = this._router.events.subscribe((e: any) => {
      // If it is a NavigationEnd event re-initalise the component
      if (e instanceof NavigationEnd) {
        this.initialiseComponent();
      }
    });
  }

  initialiseComponent() {
    this.getDocuments();
  }
  ngOnDestroy() {
    // avoid memory leaks here by cleaning up after ourselves. If we
    // don't then we will continue to run our initialiseInvites()
    // method on every navigationEnd event.
    if (this.navigationSubscription) {
      this.navigationSubscription.unsubscribe();
    }
  }

  ngOnInit() {
    this.getDocuments();
  }

  getDocuments() {
    this._route.paramMap.subscribe(params => {
      this.department = params.get("department");
    });

    this._documentService
      .getDocumentsByDepartment(this.department)
      .subscribe(response => {
        this.documents = response["documents"];
        console.log(response["documents"]);
      });
  }
}

--------- 相同的 HTML 组件 ------------

<app-documents-view [docs]="documents"></app-documents-view>

------------ 查看组件 TS ------------

import { Component, OnInit, Input } from "@angular/core";
import { DocumentService } from "src/app/services/document.service";
import { saveAs } from "file-saver";
import { faEye, faDownload } from "@fortawesome/free-solid-svg-icons";

@Component({
  selector: "app-documents-view",
  templateUrl: "./documents-view.component.html",
  styleUrls: ["./documents-view.component.css"]
})
export class DocumentsViewComponent implements OnInit {
  // ICONS
  faEye = faEye;
  faDownload = faDownload;

  @Input() docs; // loaded with documents from parent component (@Output())
  showDocumentListing = true;
  showFileViewer = false;
  fileUrl; // Used to set the view document viwer (ngx-viewer)

  constructor(private _documentService: DocumentService) {}

  ngOnInit() {}

  viewDocument(id) {
    this._documentService.getDocument(id).subscribe(response => {
      this.fileUrl = response["documentUrl"];
      this.showDocumentListing = false;
      this.showFileViewer = true;
    });
  }

  downloadDocument(id) {
    this._documentService.getDocument(id).subscribe(response => {
      saveAs(response["documentUrl"], response["documentKey"]);
    });
  }

  closeDocumentView() {
    this.showFileViewer = false;
    this.showDocumentListing = true;
  }
}

---------- 查看组件 HTML ------------

<div class="card" *ngIf="docs && showDocumentListing">
  <div class="card-header bg-light text-primary">
    <h3>Documents</h3>
  </div>
  <div class="card-body border border-light">
    <div class="table-responsive mt-3">
      <table class="table">
        <thead>
          <th>Filename</th>
          <th>Description</th>
          <th>Action</th>
        </thead>
        <tbody>
          <tr *ngFor="let doc of docs">
            <td>{{ doc?.key }}</td>
            <td>{{ doc?.description }}</td>
            <td>
              <button class="btn btn-primary mr-1" (click)="viewDocument(doc._id)">
                <fa-icon [icon]="faEye"></fa-icon>
              </button>
              <button class="btn btn-primary" (click)="downloadDocument(doc._id)">
                <fa-icon [icon]="faDownload"></fa-icon>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

标签: htmlangulartypescript

解决方案


线路有问题 @Output() documents = new EventEmitter();

您只需要将道具传递给子组件。您不需要这个,它用于将某些事件从孩子传达给父母。这里发生的情况是,第一次渲染使用文档属性作为 Event Emitter 对象发生,这会导致此 *ngFor 错误,并且在您获得响应后,它在第二次渲染中工作正常。

您可以删除此文档的属性分配,它应该可以正常工作。


推荐阅读