我目前正在尝试使用Angular 8从我的api中获取数据。数据应具有TaskInterface的结构。
请在下面查看我的代码和说明:
TaskInterface:
export interface TaskInterface {
id: number;
name: string;
description: string;
due_date: string;
done: number;
created_at: string;
updated_at: string;
user: object;
}
TaskListService:
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`);
}
}
TaskListComponent:
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传递,并且页面仍为白色,并且控制台显示: 错误错误:尝试与'[object Object]'进行比较时出错。仅允许数组和可迭代对象。 对象内是包含关键数据的数组。我是否可以通过订阅方法将关键数据添加到任务属性中?
this.tasks = task.data;
...出现在主题行中的错误消息,... 错误TS2339:类型'TaskInterface []'不存在属性'data' ...但是数据可以通过这种方式在模板中正确呈现。
如果我在subscribe方法中将任务属性转换为任意类型,我可以解决此问题...
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>
答案 0 :(得分:1)
您可以通过getAll
方法更正类型,如下所示:
getAll(): Observable<{data: TaskInterface[]}> {
return this.http.get<{data: TaskInterface[]}>( `${this.api}/tasks`);
}
然后,订阅getAll
,task
在TaskInterface
属性中将有一个data
数组:
this.taskService.getAll()
.subscribe((task) => {
this.tasks = task.data; // safe to use, because task is now {data: TaskInterface[]}
});