Angular Http Client

learn how to use HttpClient to fetch and alter the data

  • Standard HttpClient in Angular
  • Get, Post, Put, Delete - all what's needed for http
  • Returns Observable from rxjs
  • Works with JSON out of the box

Import HttpClientModule

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

@NgModule({
  declarations: [],
  imports: [
    HttpClientModule,
    ...
    ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Import Http Client

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

constructor(
	private httpClient: HttpClient,
) { }

...

getVideos(): Observable<any> {
	return this.httpClient.get("http://localhost:3000/video");
}

setVideo(data: any): Observable<any> {
	return this.httpClient.post("http://localhost:3000/video", data);
}

Better approach

  • Move httpClient usage inside separate class
  • Use Injectable Service
  • Take URL from environment.ts
  • Use interfaces
  • Subscribe in component

Environment.ts

export const environment = {
  production: false,
  apiUrl: ' http://localhost:3000',
};

Video Interface

export interface VideoModel {
  id: string;
  title: string;
  views: number;
  likes: number;
  dislikes: number;
}

Video Service

@Injectable({
  providedIn: 'root',
})
export class AppService {

  constructor(private httpClient: HttpClient) { }

  getVideos(): Observable<any> {
      return this.httpClient.get(`${environment.apiUrl}/video`);
  }
}

Generic Mapping <>

@Injectable({
  providedIn: 'root',
})
export class AppService {

  constructor(private httpClient: HttpClient) { }

  getVideos(): Observable<VideoModel[]> {
    return this.httpClient.get<VideoModel[]>(
    	`${environment.apiUrl}/video`)
  }
}

Custom Mapping

@Injectable({
  providedIn: 'root',
})
export class AppService {

  constructor(private httpClient: HttpClient) { }

  getVideoIds(): Observable<string[]> {
    return this.httpClient.get<VideoModel[]>(
    	`${environment.apiUrl}/video`)
      .pipe(map((data: any[]) => {
        return data.map(x => x.id);
      }));
 }
}
@Injectable({
  providedIn: 'root',
})
export class AppService {

  constructor(private httpClient: HttpClient) { }

  getVideoById(id: string): Observable<VideoModel> {
    return this.httpClient.get<VideoModel>(
   		`${environment.apiUrl}/video/${id}`);
  }
}

URL Routing

@Injectable({
  providedIn: 'root',
})
export class AppService {

  constructor(private httpClient: HttpClient) { }

  getVideoById(param1: number, param2: string): Observable<VideoModel> {
    return this.httpClient.get<VideoModel>(
   `${environment.apiUrl}/video/?param1=${param1}&param2=${param2}`);
  }
}

URL Routing

@Injectable({
  providedIn: 'root',
})
export class AppService {

 constructor(private httpClient: HttpClient) { }

 getWithParams(param1: number, param2: string): Observable<VideoModel[]> {
    	const params = new HttpParams();
	params.set('param1', param1.toString())
    	params.set('param2', param2)

    	return this.httpClient.get<VideoModel[]>(
        	`${environment.apiUrl}/video`, { params });
  }
}

Query Parameters

options?: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }

Options

Reliability

@Injectable({
  providedIn: 'root',
})
export class AppService {

  constructor(private httpClient: HttpClient) { }

  getVideos(): Observable<VideoModel[]> {
   return this.httpClient.get<VideoModel[]>(`${environment.apiUrl}/video`)
      .pipe(
        retry(3),
        catchError((error: any, caught: Observable<VideoModel[]>) => {
          console.log(error);
          return caught;
        })
      );
  }
}

Let's try!

// run server

// open other terminal / cmd

cd server
npm start

http://localhost:3000/video

Made with Slides.com