Skip to content

Instantly share code, notes, and snippets.

@krishna-acondy
Last active June 8, 2020 19:20
Show Gist options
  • Save krishna-acondy/0f4d63f34ed4eda1ebb449cf72e3277a to your computer and use it in GitHub Desktop.
Save krishna-acondy/0f4d63f34ed4eda1ebb449cf72e3277a to your computer and use it in GitHub Desktop.
Generic Angular Sub-Resource Service
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));
}
}
@kenobi-io
Copy link

How you injects generic service in angular?

@EigenTheory
Copy link

What is QueryOptions?

@krishna-acondy
Copy link
Author

@krishna-acondy
Copy link
Author

krishna-acondy commented Jun 8, 2020

@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