1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Emit subscribed values for output

Discussão em 'Angular' iniciado por Sergej Bjakow, Outubro 10, 2024 às 07:22.

  1. In Angular, is it a good practice to get an observable, subscribe to it and emit that very value via EventEmitter as an Output?

    in my Example I have a ParentComponent, that receives a plain Object "product" as an InputParameter, but within the SubComponent I am going to receive new productData as an Observable that I need to pass back up via Output and update the initial plain Product-object. I have variant-Data that is handled in the subcomponent and once I click on a Variant Entry, new ProductData is fetched from the server that is supposed to refresh the current data view in the Parent component. Here is the code

    ##########ParentComponent##########
    TS:
    export class ProductViewComponent {

    @Input()
    product: Product;

    updateProduct(newVariantProduct: Product) {
    this.product = newVariantProduct;
    }
    }

    HTML:

    <div>{{product.name}} - {{product.price}}</div>
    <app-variants
    [variants]="product.variants" (getVariant)="updateProduct($event)">
    </app-variants>

    ##########ChildComponent##########
    TS:
    export class ProductVariantsComponent {

    @Input()
    variants: ProductVariants[];

    @Output() getVariant = new EventEmitter<any>();

    loadProduct(variant: EmvProductColorVariant){
    this.productService.getProduct(variant.code).subscribe(p => {
    productColorVariant.emit(p);
    });
    }
    }

    HTML:
    <li
    *ngFor="let variant of variants"
    (click)="loadProduct(variant)">
    <img *ngIf="variant.picture" [src]="variant.picture" />
    </li>


    Should I go for that approach (of course unsubscribing too eventually), or is there a better way to do this? I'm generally not a fan of using "subscribe" and this looks very fishy to me, but I'm not sure what alternative there is...

    Thanks for helping

    Continue reading...

Compartilhe esta Página