Transformation occurs once you subscribe to an observable entity

Within the x.component.ts, I initiate the getSomething() method from y.service.ts. Since this method returns an observable, I subscribe to it. However, I encounter a peculiar issue where an object with 4 elements, one being an array of number arrays (number[][]), becomes empty after the subscription.

In my x.component.ts file:

this.y
      .getSomething()
      .pipe(
        //create an observable to pass to child component 
        tap(data => (this.pautaFinal$ = of(data))),
        //This object is used for development purposes
        tap(data => (this.pautaFinal = data)),
        //Convert the number[][] object into a number[][][]
        //which is necessary
        tap(
          data =>
            (this.escalaPorcionada = this.transformEscala(
              data.escala.escalaArr,
              10
            ))
        )
      )
      .subscribe();

// Convert an array of number arrays into an array of arrays containing chunkSize number arrays.
transformEscala(escala: number[][] = [], chunkSize: number): number[][][] {
    let results: number[][][] = [];
    while (escala.length) {
      results.push(escala.splice(0, chunkSize));
    }
    return results;
  }

Additionally, in x.component, I tried replacing the third tap with a map(data => data.escala.escala) and then `.subscribe(data => this.escalaPorcionada = this.transformEscala(data, 10).

In y.service.ts:
  getSomething(): Observable<Pauta> {
    let admin: DatosAdmin;
    let escala: Escala;
    let rubrica: Rubrica;
    let criterios: Criterios;
    this.datosAdminAcumul$.subscribe(datos => (admin = datos));    
    this.escalaAcumul$.subscribe(datos => (escala = datos));
    this.rubricaAcumul$.subscribe(datos => (rubrica = datos));
    this.criteriosAcumul$.subscribe(datos => (criterios = datos));

    let user = JSON.parse(localStorage.getItem("user"));

    // Additional data to add to Pauta.
    let extras = {
      usuarioModificacion: user.id
    };

    const pautaFinal: Pauta = {
      datosAdmin: admin,
      criterios: criterios,
      rubrica: rubrica,
      escala: escala,
      extras: extras
    };
    return of(pautaFinal);
  }

The function within y.service.ts contains multiple observables within the same service, subscribes to them, retrieves values, assigns these values to other variables, and finally encapsulates all of them inside a pautaFinal object, which is then returned as an observable.

Attempts Made: I have inspected the array using Chrome debugger tool and confirmed that it exists before the subscription but turns empty afterward.

This is the visualization of escalaArr within the observable this.escalaAcumul$ (from y.service) https://i.sstatic.net/zMQ4a.jpg

This image displays the scenario post-subscription. This snapshot was taken right after the previous instance. https://i.sstatic.net/e6pKv.jpg

The object contains 4 more elements, none of which undergo any changes apart from the escalaArr.

I am puzzled about what might be going wrong here. I've been grappling with this problem for some time now and would greatly appreciate any assistance. Thank you.

Answer №1

To prevent the 'by reference'-chain of JavaScript, it is recommended to clone the object received from the Observable before processing it.

this.y
  .getSomething()
  .pipe(
    // Creating an observable to pass to a child component 
    tap(data => (this.pautaFinal$ = of(data))),
    // Development purposes only - storing the data in this.pautaFinal
    tap(data => (this.pautaFinal = data)),
    // Converting number[][] object into number[][][] format as required
    tap(
      data =>
        (this.escalaPorcionada = this.transformEscala(
          Object.assign({}, data.escala.escalaArr), // <-- cloning here to avoid modification of original object
          10
        ))
    )
  )
  .subscribe();

If the issue persists, ensure that no other component has access to the setter of your Observable.

EDIT:

Option 2:

transformEscala(escala: number[][] = [], chunkSize: number): number[][][] {
    let results: number[][][] = [];
    const clone = Object.assign({}, escala);

while (clone.length) {
  results.push(clone.splice(0, chunkSize));
}
return results;

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come ngOnChange is unable to detect changes in @Input elements when ngOnDetect is able to do so?

Check out this plunker Please note: In order to see the effect, you need to restart the app after entering the link. import {Component, OnInit, Input, OnChanges, DoCheck} from 'angular2/core' @Component({ selector: 'sub', templat ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

Angular: cut down lengthy text with an ellipsis and display more upon click

I am currently working with Angular 8, Angular Material, and Bootstrap utilities. Below is the code snippet I have been using: <div class="p-1 text-break" *ngSwitchDefault [innerHTML]="cell.value | longText"& ...

Master your code with Rxjs optimization

Looking at a block of code: if (this.organization) { this.orgService.updateOrganization(this.createOrganizationForm.value).subscribe(() => { this.alertify.success(`Organization ${this.organization.name} was updated`); this.dialogRef.close(true ...

Angular 4: Unable to attach 'ngModel' to 'input' as it is not recognized as a valid property

Before flagging as duplicate, please take a moment to review: Hello there! I am currently delving into the world of Angular 4 and ASP.Net Core, and I've encountered an issue that has been puzzling me. Despite exploring various similar problems where ...

Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data. data = ['middlename.firstname.lastname','firstname.lastname']; During the process, I am looping through the .html usin ...

Extending an interface in TypeScript does not permit the overriding of properties

While working with Typescript, I encountered an issue where I couldn't make a property not required when overwriting it. I have defined two interfaces: interface IField { label: string; model: string; placeholder? ...

How to compare and filter items from two arrays using TypeScript

I am looking to filter out certain elements from an array in TypeScript Original Array: [ {"Id":"3","DisplayName":"Fax"}, {"Id":"1","DisplayName":"Home"}, {"Id":&quo ...

Encountering an error with TypeScript generic parameters: Expecting '?' but receiving an error message

As a newcomer to TypeScript, I am currently exploring the use of generic type parameters. I have encountered an error message: '?' expected while working on a function and a type that both require type arguments. The issue seems to be in the Inpu ...

Creating Instances of Variables Within a Class

Currently, I am working on a project using Ionic and Angular. I have come across various ways of instantiating variables and I'm unsure about the implications of each method. Here are three scenarios that confuse me: export class someClass { myVaria ...

Angular 14: Enhance Your User Experience with Dynamic Angular Material Table Row Management

My inquiry: I have encountered an issue with the Angular material table. After installing and setting up my first table, I created a function to delete the last row. However, the table is not refreshing as expected. It only updates when I make a site chang ...

Problem encountered while implementing callbacks in redux-saga

I am facing a scenario in which I have a function called onGetCameras that takes a callback function named getCamerasSuccess. The idea is to invoke the external function onGetCameras, which makes an AJAX call and then calls getCamerasSuccess upon completio ...

Reactify TypeScript: Accurate typings for onChange event

How can I resolve the issues with types for target: { value: any, name: any }? The errors I encounter include Duplicate identifier 'any'. and Binding element 'any' implicitly has an 'any' type.. Additionally, why does the erro ...

In order to either pass a component variable as a parameter or set it as a global variable

Currently, I am in the process of restructuring my Angular2/Ionic2 code and seeking advice on the best practice for my specific situation. Within my component, I have declared a variable (this.questions) that I need to utilize in my service method. There ...

Encountering an "Undefined property" error in Angular when trying to read a property, even though the json-p

manager.ts export interface Manager { id: number; name: string; employees: Array<Employee>; } employee.ts export interface Employee { id: number; fullName: string; } managers.component.ts export class ManagersComponent implem ...

A step-by-step guide on injecting a model within the root app module of a Nest JS application

Hello, I encountered an error in my Nest app and here is a screenshot of the error: https://i.stack.imgur.com/zY1io.png Below is the code snippet for the AppModule: @Module({ imports: [AppModule,CrudModule,MongooseModule.forRoot("mongodb://localhost:2 ...

Encountering "Object is possibly undefined" during NextJS Typescript build process - troubleshooting nextjs build

I recently started working with TypeScript and encountered a problem during nextjs build. While the code runs smoothly in my browser, executing nextjs build results in the error shown below. I attempted various solutions found online but none have worked s ...

The Angular interceptor is highlighting an issue with the catchError operator

I'm currently working on creating an interceptor to manage HTTP errors in my Angular 10 project. Check out the code snippet below: import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http'; imp ...

Angular-12 ngx-datatable does not recognize the element 'ngx-caption' in Angular

Within my Angular-12 project, I have set up two modules: AppModule and AdminModule. Specifically, I am utilizing the following module for datatable functionality: "@swimlane/ngx-datatable": "^19.0.0", Here is how it is implemented in ...

How can Angular CLI prevent the submission of an HTML form unless a previous option has been selected

I am currently working on a form that contains select fields with various options pre-populated. <form [formGroup]="selectVehicleForm"> <select formControlName="Manufacturer"> <option *ngFor='let ...