Crud Service RXJS Angular 9命令查询模式



我正在尝试使用rxjs在angular中构建crud服务。我有产品服务可以通过getall、getbyid、post、pust、delete方法与后端通信在之上

产品facade服务,充当存储/服务,并公开组件的公共api,如下所示:

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,
};
}
}

现在我正在尝试构建两个组件用于显示产品的产品列表,如果需要,用户可以删除,并导航用户添加或编辑产品产品表单创建或编辑新表单,创建后用户返回产品列表。

产品列表.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);
}
}
}

的产品

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 });
}
}

代码的行为不同,因为它发出了多个delete put或post命令。。。不知道我在哪里犯错。。因为我是rxjs的新手。此外,欢迎就如何避免订阅ts提出任何建议。我已经用注释标记了它们(//代码需要改进。(

这是shareReplay(1)就位后的更新代码。正如我上面提到的,它是在scan之后需要的。否则,scan管理的阵列不会在操作之间得到适当的重用。

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);
})
);

我还对Stacklitz进行了更新,您可以在这里找到:https://stackblitz.com/edit/angular-crud-deborahk

尽管我在这个stackblitz中对您的原始版本进行了重大更改,包括将更新更改为一行map,将删除更改为一行将filter

最新更新