Search code examples
angularrxjsrxjs-observables

Angular 11 RxJS: How do you add an object to a nested list of objects of an observable?


Let's say I have an observable of an object in the shape of:

export interface Invoice {
  fdInvoiceID: number;
  fdInvoiceNumber: string;
  fdCustomerID: number;
  fdTotal: number
  invoiceLineItems: InvoiceLineItem[];

If the user adds a line item, how can I add that to the invoiceLineItems list of the observable?

I have an observer invoices$ and I am using async in the template

*ngIf="invoices$ | async as invoices"

After the the new lineItem is saved to the database, I want add it to the invoices$.invoiceLineItems and have it displayed via async.


Solution

  • I believe you should not use observable for that. If its data changes store in as variable and pass subscribed data to input.

    <div *ngFor="let invoice of invoices"
     [items]="invoice.items"> </div>
    

    UPDATE:

    You can combine event and invoices$ that change data like below:

    public get invoices$(): Observable<Invoice[]> {
     return combineLatest([eventThatChangesItems$, invoices$]).pipe(
       map(([invoiceLineItems, invoices]) => invoices.map(invoice) => 
         invoice.invoiceLineItems = invoiceLineItems);
       );
    }