Created
January 24, 2019 16:22
-
-
Save Rudyzio/e350ef52c018adf8c9cbf9b363c76f01 to your computer and use it in GitHub Desktop.
Angular 7 abstract data service
This file contains 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 { HttpClient } from '@angular/common/http'; | |
import { SimpleModel } from '../models/common/SimpleModel'; | |
import { Observable } from 'rxjs'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class DataService<T extends SimpleModel> { | |
private url: string = 'http://localhost:5000/api'; | |
constructor( | |
private httpClient: HttpClient, | |
private endpoint: string | |
) { } | |
getAll(): Observable<T[]> { | |
console.log("getAll"); | |
return this.httpClient | |
.get<T[]>(`${this.url}/${this.endpoint}`); | |
} | |
get(id: number): Observable<T> { | |
console.log("get", id); | |
return this.httpClient | |
.get<T>(`${this.url}/${this.endpoint}/${id}`); | |
} | |
add(item: T): Observable<T> { | |
console.log("add", item); | |
return this.httpClient | |
.post<T>(`${this.url}/${this.endpoint}`, item); | |
} | |
update(item: T): Observable<T> { | |
console.log("update", item); | |
return this.httpClient | |
.put<T>(`${this.url}/${this.endpoint}/${item.id}`, item); | |
} | |
delete(id: number) { | |
console.log("delete", id); | |
return this.httpClient | |
.delete(`${this.url}/${this.endpoint}/${id}`); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment