【发布时间】: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