gpt4 book ai didi

javascript - 如何将获取到的API的一部分添加到component中定义的数组中

转载 作者:行者123 更新时间:2023-11-29 23:47:04 25 4
gpt4 key购买 nike

为了学习,我正在尝试使用 Angular 2 + Django Rest Framework 创建一个简单的 Todo 应用程序。
为了立即显示输入表单中保存的项目,我想实现获取最新的并显示的功能。

用于获取最新的JSON格式的WEB API具有以下结构。 enter image description here

获取这个API的函数在todo.service.ts中有描述

@Injectable()
export class TodoService {
todo: Todo[] = [];
newtodo: NewTodo[] = [];
private Url = `http://127.0.0.1:8000/api/todo/`
private headers = new Headers({'Content-Type': 'application/json'});

constructor(
private http: Http
){}

// Acquire one latest todo added
getNewTodo(): Promise<NewTodo[]> {
return this.http
.get(this.Url+"?limit=1")
.toPromise()
.then(res => res.json())
.catch(this.handleError)
}

组件在 todo.component.ts 中描述

@Component({
selector: 'todo-list',
templateUrl: '../templates/todo-list.component.html',
styleUrls: ['../static/todo-list.component.css']
})
export class TodoListComponent {
todos: Todo[] = [];
newtodo: NewTodo[] = [];
newtodos: Todo[] = [];
@Input() todo: Todo = new Todo();

save(): void {
this.todoService
.create(this.todo);
}
}

我要传授的重点是以下几点。
1.在执行组件的save()时执行service的getNewTodo(),将获取到的返回值存放到newtodo数组中。
2.由于获取的json只需要results部分,将results部分拉出来,push到数组newtodos中传给html。

对于1,我觉得你应该在save()中写如下描述

this.todoService
.getNewTodo()
.then(newtodo => this.newtodo = newtodo);

我不明白要写什么 2.我想告诉你如何解决它。

最佳答案

您可以进入 JSON 并通过以下方式获取 results 的内容:

getNewTodo(): Promise<NewTodo[]> {
return this.http
.get(this.Url+"?limit=1")
.toPromise()
.then(res => res.json().results) // here
.catch(this.handleError)
}

你没有展示在服务中使用 create 方法,但不管它是什么样子,返回一个 promise ,这样我们在组件中就可以在回调中调用 getNewTodo:

save() {
this.todoService
.create(this.todo)
.then(data => {
this.getNewTodo(); // here
})
}

以及调用服务中方法的getNewTodo:

getNewTodo() {
this.todoService
.getNewTodo()
.then(newtodo => {
this.newtodo = newtodo
});
}

关于javascript - 如何将获取到的API的一部分添加到component中定义的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43623786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com