Home > database >  Angular RxJs - Crud Operations
Angular RxJs - Crud Operations

Time:03-10

public ngOnInit() {
  this.getUsers();
}

public getUsers() {
  this.userService.getUsers(this.listId).pipe(take(1)).subscribe(data => {
    if (data.result.length) {
      this.users = data.result;
    } else {
      const user = new UserModel();
      this.users = [user];
    }
    this.setupForm();
  });

}

public deleteUser(userId: number) {
  this.userService.delete(this.listId, userId)
    .subscribe(() => this.getUsers())
}

How would you recommand me, when I'm deleting an user from a table, to get back all the users? Is ok to call this.getUsers() method in .subscribe()? Or should I try to call it in .pipe()

CodePudding user response:

It depends, if you want to get fresh data from the API every time you delete then you can use switchMap operator from import { filter, map, switchMap } from 'rxjs/operators';

Here is an example of how to use it:

public deleteUser(userId: number): void {
    this.userService
      .delete(this.listId, userId)
      .pipe(switchMap(() => this.userService.getUsers(this.listId)))
      .subscribe((res) => (this.users = res));
  }

Second solution would be removing the delete item from a list of users using javascript splice function:

    public deleteUser(userId: number): void {
            this.userService
              .delete(this.listId, userId)
              .subscribe((res) => {
            const index = this.users.findIndex(u => u.userId === userId);
            if (index > -1) {
                   this.users.aplice(index, 1)
            }
            });
          }

CodePudding user response:

I usually create an observable for getting data that updates whenever there's a CRUD operation. Here is a schematic example:

edit$ = this.editClick$
  .pipe(
     switchMapTo(this.latestFormValue$),
     switchMap(formValue => this.api.edit(formValue))
  )

delete$ = this.deleteClick$
  .pipe(
    switchMap(id => this.api.delete(id))
  )

getData$ = merge(this.edit$, this.delete$)
  .pipe(
    switchMap(() => this.api.getData(this.param))
  )
  • Related