Search code examples
javascriptangularangular2-servicesangular2-components

How to add a part of the acquired API to the array defined in component


For learning, I am trying to create a simple Todo application using Angular 2 + Django Rest Framework.
In order to immediately display the items saved in the input form, I want to implement the function of acquiring the latest one and displaying it.

JSON format WEB API for acquiring the latest one has the following structure. enter image description here

function for getting this API is described in 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)
  }

Components are described in 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);
  }
}

The point I want to teach is the following points.
1.Execute service's getNewTodo () when save () of the component is executed and store the obtained return value in the array newtodo.
2.Since only the results part is necessary for the acquired JSON, pull out the results part, push it to the array newtodos and pass it to html.

For 1, I think that you should write the following description in save ()

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

I can not understand what to write about 2. I'd like to tell you how to solve it.


Solution

  • You can step into the JSON and obtain the content of results with the following:

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

    You are not showing use the create-method in the service, but whatever it looks like, return a promise, so that we in the component can inside the callback call getNewTodo:

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

    and the getNewTodo that calls the method in the service:

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