Observables Http in angular2 [closed]

0

I am developing a web application and for this I use the framework angular2 on the client ( Frontend ) and on the server ( Backend ) I have java services done in hibernate to access the data layer.

To consume the ( Backend ) services from ( Frontend ) I am using the observables but they do not work for me. Well when I insert a new value I do not refresh the list of values.

I would like someone to show me an example of the use of the observables in angular 2 consuming Http services, which will eliminate, insert and refresh the list of objects with which I am working.

    
asked by Richard Urquiza Santiesteban 28.08.2017 в 21:44
source

1 answer

0

Suppose we have the following data structure that your API (backend) responds to.

interface Task {
  id: number;
  title: string;
  description?: string | null;
  created_at?: string | Date | null;
  updated_at?: string | Date | null;
}

Well, now we have to prepare the service / provider which is in charge of obtaining / modifying data from your API or another place.

@Injectable()
export class TaskService {

  private baseUrl: string = environment.baseUrl;

  constructor(private http: HttpClient) {} // Angular 4.3+
  // constructor(private http: Http) {} // Angular 2+

  read(id: number): Observable<Task> {
    return this.http.get<Task>('${this.baseUrl}/v1/tasks/${id}');
  }

  readAll(): Observable<Task[]> {
    return this.http.get<Task[]>('${this.baseUrl}/v1/tasks');
  }

  create(task: Task): Observable<Task> {
    return this.http.post<Task>('${this.baseUrl}/v1/tasks', task);
  }

  update(task: Task): Observable<Task> {
    return this.http.put<Task>('${this.baseUrl}/v1/tasks/${task.id}', task);
  }

  delete(id: number): Observable<Task> {
    return this.http.delete<Task>('${this.baseUrl}/v1/tasks/${id}');
  }

}
  

Of course you can send what you need, in this simple example I send the example as is, and I assume that my server receives a JSON and my client receives a JSON, if you want to change the headers you can do it. The important thing is that the angular http requests return an Observable, although you can convert it into a Promise if you wish.

Let's continue. Now you need to create your component to consume your service and to update your data / list you just have to modify it. Be careful, you can update a data source (datasource) in many ways, this is the most classic, the mutable.

@Component({
  selector: 'app-tasks',
  templateUrl: './tasks.component.html',
  styleUrls: ['./tasks.component.css'],
})
export class TasksComponent implements OnInit {

  tasks = new Array<Task>();

  constructor(private taskService: TaskService) {}

  ngOnInit() {
    this.readTasks();
  }

  createTask(task: Task) {
    this.taskService.create(task).subscribe(
      (taskCreated: Task) => {
        this.tasks.push(taskCreated);
        console.log('createTask: OK')
      },
      (err: any) => console.error('createTask: ERROR')
    )
  }


  readTasks() {
    this.taskService.readAll().subscribe(
      (tasks: Task[]) => {
        this.tasks = tasks;
        console.log('readTasks: OK')
      },
      (err: any) => console.error('readTasks: ERROR')
    )
  }

  updateTask(task: Task) {
    this.taskService.update(task).subscribe(
      (taskUpdated: Task) => {
        const index = this.tasks.findIndex(t => t.id === taskUpdated.id);
        if (index > -1) {
          this.tasks[index] = taskUpdated;
        }
        console.log('updateTask: OK')
      },
      (err: any) => console.error('updateTask: ERROR')
    )
  }

  deleteTask(task: Task) {
    this.taskService.delete(task).subscribe(
      (taskDeleted: Task) => {
        this.tasks = this.tasks.filter(t => t.id !== taskDeleted.id);
        console.log('deleteTask: OK')
      },
      (err: any) => console.error('deleteTask: ERROR')
    )
  }
}

And that's it, but do not forget to import your service in the module that your component is located, usually if you do not use more modules than the main AppModule that's where you should be, both the service / provider and the module Http of Angular, that there are 2: HttpModule (Angular 2) and HttpClientModule (from Angular 4.3).

@NgModule({
  imports: [HttpModule, HttpClientModule],
  declarations: [TasksComponent],
  providers: [TaskService],
  exports: [TasksComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}
    
answered by 28.08.2017 / 22:24
source