Home > OS >  Angular service to change multiple variable values
Angular service to change multiple variable values

Time:08-11

I have two components that have some similarities in the TypeScript side. Both of the components share the same logic in one method so there is duplicated code for the two components. I would like to have that duplicated code/method in a service and call the method from there. My problem is that in this method I have few variables that need to be changed for the component usage and I'm not sure how to achieve that. I know how to return a single value from service method but not sure how to change multiple variable values.

Component 1 & 2 method which I would put to Service:

editCustomProduct(index: number, customProduct: CustomProduct) {
        this.currentEditingProduct = plainToClass(CustomProduct, customProduct);
        this.currentEditingIndex = index;
        if (customProduct.productId) {
            if (customProduct.productType === ProductType.CUSTOM) {
                this.productService.find(customProduct.productId).subscribe((p: CustomProduct) => {
                    this.searchedProduct = p;
                });
            }
        }
}

So the values I need for the Component are:

  • currentEditingProduct
  • currentEditingIndex
  • searchedProduct

What would be your approach here?

CodePudding user response:

You should return an object of an obsevable:

editCustomProduct(index: number, customProduct: CustomProduct):Observable<{currentEditingProduct: CustomProduct, currentEditingIndex:number, searchedProduct?:CustomProduct}> {
    if (customProduct.productId && ustomProduct.productType === ProductType.CUSTOM) {
        this.productService.find(customProduct.productId).map(
            (p: CustomProduct) => {
                return {
                    currentEditingProduct: plainToClass(CustomProduct, customProduct),
                    currentEditingIndex: index,
                    searchedProduct: p
                };
            }
        );
    }else{
        return of({
            currentEditingProduct: plainToClass(CustomProduct, customProduct),
            currentEditingIndex: index
        });
    }
}

in your component you do:

this.myService.editCustomProduct$(index, customProduct).subscribe(
    res =>{
        this.currentEditingProduct = res.currentEditingProduct;
        this.currentEditingIndex = res.currentEditingIndex;
        if(res.searchedProduct){
            this.searchedProduct = res.searchedProduct;
        }
    }
); 
  • Related