Skip to content

Instantly share code, notes, and snippets.

@jonstorer
Last active December 20, 2019 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonstorer/2b10f08d932b207da03458d5b4953ec6 to your computer and use it in GitHub Desktop.
Save jonstorer/2b10f08d932b207da03458d5b4953ec6 to your computer and use it in GitHub Desktop.
angular service
<div class="widgets-list-container">
</div>
import { Component, OnInit } from '@angular/core';
import { Widget } from './widget.model';
import { WidgetService } from './widget.service';
@Component({
templateUrl: './widget.component.html',
styleUrls: ['./widget.component.scss'],
})
export class WidgetsComponent implements OnInit {
constructor(
widgetService: WidgetService
) {}
public ngOnInit(): void {
this.widgetService.find({ }).subscribe((widgets) => {
this.widgets = widgets;
});
}
public createWidget(widget: Widget): {
this.widgetService.save(widget).subscribe((widget) => {
this.widgets.unshift(widget);
});
}
public updateWidget(widget: Widget): {
this.widgetService.save(widget).subscribe((widget) => {
let index;
for (let i=0; i<this.widgets.length; i++) {
if (this.widgets[i].id = widget.id) {
return index = i;
break;
}
}
if (index) {
this.widgets[index] = widget;
} else {
this.widgets.unshift(widget);
}
});
}
}
export interface Widget {
id: number;
name: string;
count: number;
createdAt: Date;
updatedAt: Date;
}
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Widget } from './widget.model.ts';
@Injectable()
export class WidgetService {
public url = '/api/widgets';
constructor(private http: HttpClient) {}
public find(query: object): Observable<Widget[]> {
let options = { params: new HttpParams() };
for (let key, value of Object.entries(query)) {
options.params.set(key, value);
}
return this.http.get<Widget[]>(this.url, options);
}
public findById(id: string): Observable<Widget> {
return this.http.get<Widget>(`${this.url}/${id}`);
}
public update(widget: Widget): Observable<Widget> {
let options = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return this.http.post<Widget>(this.url, widget, options);
}
public update(widget: Widget): Observable<Widget> {
let id = widget.id;
let options = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return this.http.put<Widget>(`${this.url}/${id}`, widget, options);
}
public save(widget: Widget): Observable<Widget> {
if (widget.id) {
return this.update(widget);
} else {
return this.create(widget);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment