2

で定義された配列に追加する方法学習のために、Angular 2 + Django Rest Frameworkを使用して簡単なTodoアプリケーションを作成しようとしています。
入力フォームに保存されたアイテムをすぐに表示するために、最新のものを取得して表示する機能を実装したいと考えています。
取得したAPIの一部をコンポーネント

最新のものを取得するためのJSON形式WEB APIは、以下の構造を持っています。このAPIを取得するための enter image description here

機能が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 -methodを使っ示すが、それがどのように見えるものは何でも、約束を返されていません、そのためのコンポーネントで私たちすることができますコールバックコールgetNewTodo内側:

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

やサービスのメソッドを呼び出しますgetNewTodo

getNewTodo() { 
    this.todoService 
    .getNewTodo() 
    .then(newtodo => { 
     this.newtodo = newtodo 
    }); 
} 
関連する問題