Angular

Last Updated: 9/4/2023

Getting Data

  • HttpClientModule contains all classes for working with http service
  • To consume http services import module.
  • The http class has other dependencies and we dont want to list all these in provider instead import module
  • This module has NgModule decorator applied to it and it has a provider array where all classes used in dependency injection are registered
  • Use the get() method to fetch data from a server.
  • The aynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.
  • We use promises or observables to work with asynchronous or non-blocking operations
  • We call the server - data is not available immediately - there is going to be some delay - we don't want the main thread executing the code to get blocked - we use promises and observables - with these classes when the result is ready, we will be notified
  • Observable has a method called subscribe - subscribing to observable - when the result is ready we will be notified

In app.module.ts

import {HttpClientModule} from '@angular/common/http'

Add to imports array

imports: [HttpClientModule] 

Create post.component.ts

import {HttpClient} from '@angular/common/http'

posts: any[]

constructor(private http: HttpClient) {
	http.get(url).subscribe(data => {
		this.posts = data;
 	})
}