2
中定義的數組爲了學習,我正在嘗試使用Angular 2 + Django Rest Framework創建一個簡單的Todo應用程序。
爲了立即顯示保存在輸入表單中的項目,我想要實現獲取最新的項目並顯示它的功能。
如何將部分獲得的API添加到組件
功能獲得此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 我想告訴你如何解決這個問題。