Using the Angular HTTP service

Now, we will replace the existing implementation using static data inside of the service to one using the HTTP service. To do this, we call the http.get() method on the HTTP service to fetch data, but we also need to use the map operator to get a result we can display outwards:

import { HttpClient } from '@angular/common/http';
import { Task } from './task.model';

export default class TaskService {
constructor(private http:HttpClient) {}

getTasks(): Observable<Task[]> {
return this.http.get<Task[]>(`tasks.json`)
}
}

To use the previously defined service, we just need to tell the module about it. We do so by adding it to the providers keyword:

// app/tasks/task.module.ts

@NgModule({
imports: [ /* add dependant modules here */ ],
declarations: [ ./* add components and directives here */ ]
providers: [TaskService],
})
export class TaskModule {}

Thereafter, we need to inject the TaskService in a consumer component and display it in a suitable way:

// app/tasks/task.component.ts

@Component({
template: `
<div *ngFor="let task of tasks">
{{ task.name }}
</div>
`
})
export class TasksComponent {
tasks:Task[];
constructor(private taskService:TaskService){
this.taskService.getTasks().subscribe( tasks => this.tasks = tasks)
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset