【问题标题】:error TS2339: Property 'data' does not exist on type 'TaskInterface[]'错误 TS2339:“TaskInterface []”类型上不存在属性“数据”
【发布时间】:2020-02-14 06:32:20
【问题描述】:

我目前正在尝试使用 Angular 8 从我的 api 获取数据。数据应该具有 TaskInterface 的结构。

请看我的代码和下面的解释:

任务接口:

export interface TaskInterface {
 id: number;
 name: string;
 description: string;
 due_date: string;
 done: number;
 created_at: string;
 updated_at: string;
 user: object;
}

任务列表服务:

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {TaskInterface} from './task-interface';

@Injectable({
 providedIn: 'root'
})

export class TaskListService {

private api = 'http://learning_database.test/api';

constructor(private http: HttpClient) {
}

getAll(): Observable<TaskInterface[]> {
  return this.http.get<TaskInterface[]>( `${this.api}/tasks`);
}
}

任务列表组件:

import { Component, OnInit } from '@angular/core';
import {TaskListService} from '../shared/task-list.service';
import {TaskInterface} from '../shared/task-interface';

@Component({
selector: 'app-task-list',
templateUrl: './task-list.component.html',
styleUrls: ['./task-list.component.css']
})
export class TaskListComponent implements OnInit {

private tasks: TaskInterface[] = [];

constructor(private taskService: TaskListService) { }

ngOnInit() {
this.taskService.getAll()
  .subscribe((task) => {
    this.tasks = task;
 });
}
}

来自 Api 的响应数据表明 this.tasks 是一个对象。因此,数据不会通过模板中的 ngFor,页面保持白色,控制台显示: ERROR 错误:尝试比较“[object Object]”时出错。只允许使用数组和可迭代对象。 对象内是一个包含关键数据的数组。是否在subscribe方法中将关键数据添加到task-property...

this.tasks = task.data;

...出现主题行中提到的错误消息,... 错误 TS2339:“TaskInterface[]”类型上不存在属性“数据” ...但数据在模板中以这种方式正确呈现。

如果我将 subscribe 方法中的 task-property 转换为键入任何内容,我可以解决这个问题...

this.taskService.getAll()
  .subscribe((task: any) => {
    this.tasks = task;
 });

...一切正常。但我认为这不是最佳实践,因为数据应该具有的 TaskInterface 类型。

我是否应该通过服务中的 .pipe() 和 map() 无论如何转换数据?不幸的是,我不知道该怎么做。

感谢您的建议...

任务列表组件的 HTML 文件:

<div class="ui middle aligned selection divided list">
 <div *ngFor="let task of tasks; let i = index">
  {{ task.id }}
 </div>
</div>

【问题讨论】:

  • 您的线索是错误消息,它告诉我您的 api 返回一个对象,其中包含一个名为 data 的项目,它是一个数组?你需要使用这个数据数组,而不是输入对象。

标签: angular


【解决方案1】:

您可以更正getAll 方法中的类型,如下所示:

getAll(): Observable<{data: TaskInterface[]}> {
  return this.http.get<{data: TaskInterface[]}>( `${this.api}/tasks`);
}

然后,订阅getAlltask 将在data 属性中拥有一个TaskInterface 数组:

this.taskService.getAll()
  .subscribe((task) => {
    this.tasks = task.data; // safe to use, because task is now {data: TaskInterface[]}
  });

【讨论】:

    猜你喜欢
    • 2019-01-21
    • 2016-08-13
    • 2017-12-20
    • 2016-11-14
    • 2017-10-24
    • 2021-08-10
    • 2018-11-17
    • 2020-09-25
    • 2021-06-22
    相关资源
    最近更新 更多