I have a component that gets data from server. My service has a BehaviorSubject<any[]>([])
to get data.
export class AppComponent {
items: Observable<any[]>;
constructor(private service: MyService) {
this.items = service.getItems();
// this items format is like: `[{id:1,name:'cat'},{id:2,name:'dog'}]`
}
addItem(item:any){
// add item to `this.items` observable array ???
}
removeItem(item:any){
// remove item from `this.items` observable array ???
}
}
And my service is like following:
@Injectable()
export class MyService{
private items = new BehaviorSubject<any[]>([]);
constructor(private http: HttpClient) {
this.loadItems();
}
private loadItems() {
this.http.get<any[]>('/api/items')
.subscribe((i) => this.items.next(i));
}
getItems() {
return this.items.asObservable();
}
addItem(item: any) {
return this.http
.post<any>('/api/items', item)
.subscribe(() => this.loadItems());
}
}
I need to add add and remove an item to this observable array but could not do it. The service can add data to server, but I need to add array without send to server. Is this possible?