import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { EMPTY, Observable, of, range } from 'rxjs'; import { catchError, map, shareReplay } from 'rxjs/operators'; export class DataService { private apiUrl = 'https://api.myjson.com/bins'; private httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' }); private endPoint: string; constructor(private http: HttpClient, endPoint: string, apiUrl?:string) { if(apiUrl){ this.apiUrl = apiUrl; } this.endPoint = endPoint; } getValues(): Observable { const url = `${this.apiUrl}/${this.endPoint}`; const response = this.http.get(url); return response; } getSomething(): Observable { return this.http.get(this.getUrl()); } getEntities(params?: {}): Observable { let httpParams: HttpParams; if (params) { for (let param in params) { httpParams = new HttpParams().append(param, params[param]); } } return this.http.get(this.getUrl(), { params: httpParams }) .pipe(shareReplay()); } getEntity(id?: number, params?: {}): Observable { if (id) { return this.http.get(`${this.getUrl()}/${id}`); } else if (params) { let httpParams: HttpParams; for (let param in params) { httpParams = new HttpParams().append(param, params[param]); } return this.http.get(this.getUrl(), { params: httpParams }); } return EMPTY; } private getUrl(): string { return `${this.apiUrl}/${this.endPoint}`; } doSomething() { console.log('doing something') const url = `${this.apiUrl}/${this.endPoint}`; //let response = this.http.get(url).pipe(map(s => ({id: s}))).subscribe(s => console.log(s)); // let response = this.http.get(url) range(1, 5) .pipe(map(x => ({ id: x }))) .subscribe(x => console.log(x)); } saveValue(params?: {}): Observable { return this.http.post(this.getUrl(), JSON.stringify(params), { headers: this.httpHeaders }) .pipe(catchError((e, c) => { console.log(e); return of(e); })); } }