首页 > 解决方案 > 错误 错误:找不到类型为“object”Angular 的不同支持对象“[object Object]”

问题描述

我做错了什么?这是工作,但我在我的控制台上得到了这个错误。

我的模型:

export class Form {
  id: number;
  formTaxID: number;
  name: string;
  formYear: number;
  sectionID: number;
  createdAt?: Date;
  updatedAt?: Date;
}

我的服务:

  public getAllForms(): Observable<Form> {
    return this._network.get(this.baseUrl, GlobalAPI.endpoints.forms.base).
      pipe(map(response => (response.data.forms)));
  }

form.facade.ts:

@Injectable({ providedIn: 'root' })
export class FormsFacade {
  forms$: BehaviorSubject<Form> = new BehaviorSubject(new Form());

  // Lifecycle
  constructor(private _formsAPI: FormsApi, private _router: Router) {
  }

  // Methods
  getAllForms() {
    this._formsAPI.getAllForms()
    .subscribe(forms => {
      this.forms$.next(forms);
    });
  }
}

组件 ts:

export class HomeComponent implements OnInit {
  forms$ = this._formsFacade.forms$;

  constructor(private _formsFacade: FormsFacade) {
  }

  ngOnInit(): void {
    this._formsFacade.getAllForms();
  }

}

模板:

    <div class="table-container" *ngIf="forms$ | async as forms">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">a</th>
            <th scope="col">b</th>
            <th scope="col">c/th>
            <th scope="col">d</th>
            <th scope="col">e</th>
            <th scope="col">f</th>
          </tr>
        </thead>
        <tbody *ngFor="let form of forms">
            <tr>
            <td>{{form.formTaxID}}</td>
            <a [routerLink]="['edit-form/', form.id]">
              {{ form.name }}</a>
            <td>{{form.formYear}}</td>
            <td>{{form.sectionID}}</td>
            <td>{{form.createdAt | date: 'dd/MM/yyyy בשעה hh:mm '}}</td>
            <td>{{form.updatedAt | date: 'dd/MM/yyyy בשעה hh:mm '}}</td>
          </tr>
        </tbody>
      </table>
    </div>
</div>

它的工作,但我在我的控制台上得到了这个错误。

我尝试更改为

  public getAllForms(): Observable<Form[]> {
    return this._network.get(this.baseUrl, GlobalAPI.endpoints.forms.base).
      pipe(map(response => (response.data.forms)));
  }

但是我的门面出现了这个错误

rgument of type 'Form[]' is not assignable to parameter of type 'Form'.
  Type 'Form[]' is missing the following properties from type 'Form': id, formTaxID, name, formYear, sectionIDts(2345)

问题是“ng for”无法将其识别为对象数组。如何在我的控制台上修复此错误?

标签: htmlangulartypescriptobservable

解决方案


Facade 中的问题可以纠正为:

@Injectable({ providedIn: 'root' })
export class FormsFacade {
  forms$: BehaviorSubject<Form> = new BehaviorSubject(new Form());

  // Lifecycle
  constructor(private _formsAPI: FormsApi, private _router: Router) {
  }

  // Methods
  getAllForms() {
    this._formsAPI.getAllForms()
    .subscribe(forms => {
      forms.forEach((form)=>{
          this.forms$.next(form);
      });

    });
  }
}

因为 forms$ 变量是具有单个表单的 BehaviorSubject。


推荐阅读