Last active
June 8, 2020 19:20
-
-
Save krishna-acondy/0f4d63f34ed4eda1ebb449cf72e3277a to your computer and use it in GitHub Desktop.
Generic Angular Sub-Resource 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
export class SubResourceService<T extends Resource> { | |
constructor( | |
private httpClient: HttpClient, | |
private url: string, | |
private parentEndpoint: string, | |
private endpoint: string, | |
private serializer: Serializer) { } | |
public create(item: T): Observable<T> { | |
return this.httpClient | |
.post<T>(`${this.url}/${this.parentEndpoint}/${item.parentId}/${this.endpoint}`, | |
this.serializer.fromJson(item)) | |
.pipe(map((data: any) => this.serializer.fromJson(data) as T)); | |
} | |
public update(item: T): Observable<T> { | |
return this.httpClient | |
.put<T>(`${this.url}/${this.parentEndpoint}/${item.parentId}/${this.endpoint}/${item.id}`, | |
this.serializer.toJson(item)) | |
.map((data: any) => this.serializer.fromJson(data) as T); | |
} | |
read(parentId: number, id: number): Observable<T> { | |
return this.httpClient | |
.get(`${this.url}/${this.parentEndpoint}/${parentId}/${this.endpoint}/${id}`) | |
.pipe(map((data: any) => this.serializer.fromJson(data) as T)); | |
} | |
list(parentId: number, queryOptions: QueryOptions): Observable<T[]> { | |
return this.httpClient | |
.get(`${this.url}/${this.parentEndpoint}/${parentId}/${this.endpoint}?${queryOptions.toQueryString()}`) | |
.pipe(map((data: any) => this.convertData(data.items))); | |
} | |
delete(parentId: number, id: number) { | |
return this.httpClient | |
.delete(`${this.url}/${this.parentEndpoint}/${parentId}/${this.endpoint}/${id}`); | |
} | |
protected convertData(data: any): T[] { | |
return data.map(item => this.serializer.fromJson(item)); | |
} | |
} |
What is QueryOptions?
@EigenTheory Here’s another gist which defines QueryOptions:
https://gist.github.com/krishna-acondy/0bb7110301e71ae6b641689faebbc0d9
@odobdober You can extend the generic service to make a specific service which can then be injected. For example,
class PizzaService extends ResourceService< Pizza >.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How you injects generic service in angular?