Created
July 27, 2020 10:39
-
-
Save pdashford/a158a822943aceb9bceb7a32bacc54ad to your computer and use it in GitHub Desktop.
Generic API service for Angular HTTP requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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