Skip to content

Instantly share code, notes, and snippets.

@pdashford
Created July 27, 2020 10:39
Show Gist options
  • Save pdashford/a158a822943aceb9bceb7a32bacc54ad to your computer and use it in GitHub Desktop.
Save pdashford/a158a822943aceb9bceb7a32bacc54ad to your computer and use it in GitHub Desktop.
Generic API service for Angular HTTP requests
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'
import { HttpClient, HttpHeaders, HttpEvent } from '@angular/common/http'
import { environment } from '../../../environments/environment'
import { IApiResult } from '../interfaces/api-result.interface'
import { tap, map } from 'rxjs/operators'
@Injectable()
export class ApiService {
options = {}
constructor(private httpClient: HttpClient) {
this.options = {
responseType: 'json',
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
}
get(url: string): Observable<IApiResult> {
return this.httpClient
.get<IApiResult>(`${environment.api}/${url}`, this.options)
.pipe(tap((response) => console.log(`GET: ${url}`, response)))
}
delete(url: string): Observable<IApiResult> {
return this.httpClient
.delete<IApiResult>(`${environment.api}/${url}`, this.options)
.pipe(tap((response) => console.log(`DELETE: ${url}`, response)))
post(url: string, data: any): Observable<IApiResult> {
return this.httpClient
.post<IApiResult>(`${environment.api}/${url}`, data, this.options)
.pipe(tap((response) => console.log(`POST: ${url}`, response)))
}
patch(url: string, data: any): Observable<IApiResult> {
return this.httpClient
.patch<IApiResult>(`${environment.api}/${url}`, data, this.options)
.pipe(tap((response) => console.log(`PATCH: ${url}`, response)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment