简体   繁体   中英

Push/Pop items from observable

My requirement is to show list of Employee s with CRUD operations. So I have created a HTML which subscribes an employee$ observable with async pipe to show all employee details.

Now for create employee option, i need to add a new row to employee$ observable & for delete employee, i need to remove one value from that.

Here comes the question. I need an observable in which i can add/remove/modify the values when needed. There were suggestions to use BehaviourSubject instead of Observable but i can only add things to it. I cannot remove anything from it ( for Delete i need to remove one from it).

Another option is to just subscribe the observable in the component and use the array directly instead of using async pipe which i do not want to do.

Is there any way out there to make CRUD operation in an Observable Array?

I reckon scan is a good bet:

type Command = {op: 'add', employee: Employee}|{op: 'remove', id: number}|{op: 'update', employee: Employee};

const commandSubject = new Subject<Command>();

const employees$ = commandSubject.scan((acc: Employee[], curr: Command) => {
  switch(curr.op) {
    case 'add':
      return [...acc, curr.employee];
    case 'remove':
      const newList = [...acc];
      newList.splice(acc.findIndex(employee => employee.id = curr.employeeId), 1);
      return newList;
    case 'update':
      const newList2 = [...acc];
      newList2.splice(acc.findIndex(employee => employee.id = curr.employee.id), 1, curr.employee);
      return newList2;
  }
}, []);

Also note that ngrx-store is a great tool for managing application state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM