2017-04-26 72 views
2

中定义的数组为了学习,我正在尝试使用Angular 2 + Django Rest Framework创建一个简单的Todo应用程序。
为了立即显示保存在输入表单中的项目,我想要实现获取最新的项目并显示它的功能。
如何将部分获得的API添加到组件

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()时,执行服务的getNewTodo(),并将获得的返回值存储在数组newtodo中。
2.由于只有结果部分对于获取的JSON是必需的,请将结果部分拉出,将其推送到数组newtodos并将其传递给html。

对1,我认为你应该写在保存下面的说明()

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

我不明白写什么约2 我想告诉你如何解决这个问题。

回答

1

您可以步入JSON并获得results内容有以下几点:

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

你没有显示使用create - 方法的服务,但无论它看起来像,返回一个承诺,所以我们在组件可以在回调调用getNewTodo内:

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

和调用服务的方法getNewTodo

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