Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将获取的API的一部分添加到组件中定义的数组中_Javascript_Angular_Angular2 Services_Angular2 Components - Fatal编程技术网

Javascript 如何将获取的API的一部分添加到组件中定义的数组中

Javascript 如何将获取的API的一部分添加到组件中定义的数组中,javascript,angular,angular2-services,angular2-components,Javascript,Angular,Angular2 Services,Angular2 Components,为了学习,我尝试使用Angular 2+Django Rest框架创建一个简单的Todo应用程序。 为了立即显示输入表单中保存的项目,我想实现获取最新项目并显示它的功能。 获取最新版本的JSON格式WEB API具有以下结构。 todo.service.ts中描述了获取此API的函数 @Injectable() export class TodoService { todo: Todo[] = []; newtodo: NewTodo[] = []; private Url = `

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

获取最新版本的JSON格式WEB API具有以下结构。

todo.service.ts中描述了获取此API的函数

@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)
  }
我想教的是以下几点。
1.在执行组件的save()时执行服务的getNewTodo(),并将获得的返回值存储在数组
newtodo

2.由于获取的JSON只需要结果部分,因此拉出结果部分,将其推送到数组
newtodos
,并将其传递给html。

对于1,我认为您应该在save()中编写以下描述

我不明白该写些什么。
我想告诉您如何解决它。

您可以进入JSON并通过以下方式获得
结果的内容:

getNewTodo(): Promise<NewTodo[]> {
  return this.http
    .get(this.Url+"?limit=1")
    .toPromise()
    .then(res => res.json().results) // here
    .catch(this.handleError)
}
以及调用服务中的方法的
getNewTodo

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