Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crud Service RXJS Angular 9 Command Query Pattern

I am trying to build crud service in angular using rxjs. I have product-service to communicate with backend with getall,getbyid,post,pust,delete methods and top of that

product-facade-service which act as a store/service and exposes public api for component which is as follows :

import { CrudAction, CrudOperation } from 'src/app/shared/facade-base';

@Injectable({
  providedIn: 'root'
})
export class ProductFacadeService {

  constructor(private productService: ProductClient) { }

  // All products
  getProducts$ = this.productService.get()
    .pipe(
      tap(data => console.log('Products', JSON.stringify(data))),
      //shareReplay({bufferSize:1, refCount:1,}),
      //shareReplay(1),
    );

   private productCrudActionSubject = new Subject<CrudAction<ProductResource>>();

    productsWithUpdates$ = merge(
      this.getProducts$,
      this.productCrudActionSubject.asObservable(),
    )
      .pipe(
        scan((acc: ProductResource[], action: CrudAction<ProductResource>) => {

          if(action.operation === CrudOperation.Add){
            return [...acc,action.entity];
          }

          else if(action.operation === CrudOperation.Update){
            let updatedentity = acc.find(p => p['id'] == action.entity['id']);
            updatedentity = action.entity;
            return [...acc];
          }

        else if(action.operation === CrudOperation.Delete){
          let deletedEntity = acc.find(p => p['id'] == action.entity['id']);
          const index = acc.indexOf(deletedEntity);
          if(index > - 1){
            acc.splice(index,1)
          }
        }
        return [...acc];
        }),
        catchError(err => {
          console.error(err);
          return throwError(err);
        })
      );




  private addProductSubject = new Subject<ProductResource>();
  addProductAction$ = this.addProductSubject.pipe(
    mergeMap(productToBeAdded =>this.productService.post(productToBeAdded)),
    tap(newProduct => this.productCrudActionSubject.next({operation :CrudOperation.Add,entity:newProduct}))
  );

  private updateProductSubject = new Subject<ProductResource>();
  updateProductAction$ = this.updateProductSubject.pipe(
    mergeMap(productTobeUpdated =>this.productService.put(productTobeUpdated.id,productTobeUpdated)),
    tap(updatedProduct => this.productCrudActionSubject.next({operation :CrudOperation.Update,entity:updatedProduct}))
  );

  private deleteProductSubject = new Subject<ProductResource>();
  deleteProductAction$ = this.deleteProductSubject.pipe(
    mergeMap(productToBeDeleted => this.productService.delete(productToBeDeleted.id)),
    tap(deletedProduct => this.productCrudActionSubject.next({operation :CrudOperation.Delete,entity:deletedProduct}))
    );


private productSelectedSubject = new BehaviorSubject<number>(0);
selectedProduct$ = combineLatest([
  this.productsWithUpdates$,
  this.productSelectedSubject.asObservable()
]).pipe(
  concatMap(([products, selectedProductId]) => {
    if(selectedProductId === 0){
      return of(this.intialize())
    }
    var found = products ? products.find(product => product.id == selectedProductId) : null;
    if(found){
      return of(found);
    }
    else
      return this.productService.getById(selectedProductId);
  }),
);

//Public api for component to invoke command....
save(product:ProductResource){
  product.id === 0 ?
  this.addProductSubject.next(product)
  : this.updateProductSubject.next(product);
}
deleteProduct(product:ProductResource): void {
  this.deleteProductSubject.next(product);
}
selectProduct(selectedProductId: number): void {
  this.productSelectedSubject.next(+selectedProductId);
}

  private intialize(): ProductResource {
    return {
      id: 0,
      name: 'New',
      unit : 'New',
      pricePerUnitTaxInclusive :0,
    };
  }
}

Now I am tryin to build two components product-list for showing products and user can delete if required and navigate user to add or edit product product-form to create or edit new form and when created user to go back to product-list.

product-list.ts

export class ProductListComponent implements OnInit{

  products$ = this.productService.productsWithUpdates$;


  constructor(
    private productService: ProductFacadeService,private toastr: ToastrService
    ) { }

    ngOnInit(){
//Code need improvement
      this.productService.deleteProductAction$.pipe(
        tap(deletedProduct=> this.toastr.success("Product Deleted :" + deletedProduct.name))
      ).subscribe();
    }


  onDelete(productToDelete){
    if (confirm(`Are you sure you want to delete Product : ${productToDelete.name}`)) {
      this.productService.deleteProduct(productToDelete);
      }
    }
}

product-form.ts

export class ProductFormComponent implements OnInit,OnDestroy {
  form: FormGroup = this.fb.group({
    name: ['', Validators.required],
    unit: ['', Validators.required],
    pricePerUnitTaxInclusive: [, Validators.required],
  });;

  product$= this.productClient.selectedProduct$.pipe(
    tap(res =>{
      this.form.patchValue({
        name: res.name,
        unit: res.unit,
        pricePerUnitTaxInclusive: res.pricePerUnitTaxInclusive,
      })
    })
  );

//Code need improvement
   onSave$ =  combineLatest([this.productClient.addProductAction$.pipe(tap(product => this.toastr.success("New Produt Added : " + product.name))),
                            this.productClient.updateProductAction$.pipe(tap(product => this.toastr.success("Product Updated : " + product.name)))]
                           )
                            .subscribe(() => this.onSaveComplete());

  ngOnInit() {
    this.route.params.subscribe(param => {
      this.productClient.selectProduct(param['id']);
    });
  }
  ngOnDestroy(){
    // this.onSave$.unsubscribe();
  }

  save(product:ProductResource): void {
    console.log("Save invoked")
    this.productClient.save(Object.assign({},product,this.form.value));
  }

  private onSaveComplete(): void {
    this.form.reset();
    this.router.navigate(['../'], { relativeTo: this.route });
  }
}

the codes behave differently as it issues more that one delete put or post command...dont know where i am making mistake.. as I am new to rxjs. Also any suggestions welcome for how to avoid subscribing on ts. I have marked them with comments (//Code needs improvement.)

like image 533
Shrikant Kumar Avatar asked Oct 21 '20 17:10

Shrikant Kumar


1 Answers

Here is the updated code with the shareReplay(1) in place. As I mentioned above, it's needed after the scan. Otherwise, the array managed by the scan is not reused appropriately across operations.

productsWithUpdates$ = merge(
  this.getProducts$,
  this.productCrudActionSubject.asObservable(),
)
  .pipe(
    scan((acc: PostResource[], action: CrudAction<PostResource>) => {

      if(action.operation === CrudOperation.Add){
        return [...acc,action.entity];
      }

      else if(action.operation === CrudOperation.Update){
        let updatedentity = acc.find(p => p['id'] == action.entity['id']);
        updatedentity = action.entity;
        return [...acc];
      }

    else if(action.operation === CrudOperation.Delete){
      let deletedEntity = acc.find(p => p['id'] == action.entity['id']);
      const index = acc.indexOf(deletedEntity);
      if(index > - 1){
        acc.splice(index,1)
      }
    }
    return [...acc];
    }),
    shareReplay(1),           // <----------- HERE
    catchError(err => {
      console.error(err);
      return throwError(err);
    })
  );

I also did an update to the Stackblitz that you can find here: https://stackblitz.com/edit/angular-crud-deborahk

Though I made significant changes from your original in this stackblitz, including changing the update to a one line map and the delete to a one line filter.

like image 65
DeborahK Avatar answered Oct 10 '22 00:10

DeborahK