2017-04-26 35 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 
    }); 
}