Angular doesn’t update object array after object is pushed -- [Question Asked]

Query asked by user

I am currently working on project where I use angular-google-map (agm), and I use different polygons to display different things. Now I want to draw on map so I get collection of coordinates which I can use problem is my object array doesn’t update.

TLDR: Object array doesn’t update when I use .push.

home.component.ts

export class HomeComponent implements OnInit {

ngOnInit(): void { 
}

constructor(private cr: ChangeDetectorRef) { }

//this is my polygon with initial values
pathsLs: any[] = [[
  { lat: 43.51270075713179, lng: 16.468134790981548 },
  { lat: 43.51205153579524, lng: 16.46757689150645 },
  { lat: 43.5119745090715, lng: 16.466895610416667 },
  { lat: 43.51273927004248, lng: 16.466659576023357 },
  { lat: 43.51284380496191, lng: 16.467753917301433 },
  
]]
pointList: { lat: number; lng: number }[] = [];
//this is function I use to update my Object array

addSomething() {
  this.pathsLs.push(this.pointList);
  this.pathsLs = [...this.pathsLs];
  this.cr.detectChanges();
}


Problem is when this function is called I can see on console.log(this.pathsLs) that it’s updated and it even draws polygon on map but when I refresh its all back to previous(initial value). I guess that I am asking is there a way to physically see this change for example:

if I do something like this this.pathsLs.push([{ lat: 43.51174, lng: 16.46538 }]) to actually get in my typescript this:

pathsLs: any[] = [[
    { lat: 43.51270075713179, lng: 16.468134790981548 },
    { lat: 43.51205153579524, lng: 16.46757689150645 },
    { lat: 43.5119745090715, lng: 16.466895610416667 },
    { lat: 43.51273927004248, lng: 16.466659576023357 },
    { lat: 43.51284380496191, lng: 16.467753917301433 },
    
  ],[{ lat: 43.51174, lng: 16.46538 }] <-- newly added
]

Answer we found from sources

Stackblitz

As discussed in comments, if you want persistent change to data then you’ll need to get data from persistent source like local storage or via server.

I recommend a separation of concerns approach with a service to handle storage, a container to act as a go between, and a dumb child component (reusable) that gets the data and displays it.

Use a parent container component to get the paths and pass these down to your child component displaying them:

<app-child-component [pathLs]="pathLs"></app-child-component>

The child gets the paths via @Input() and displays these

@Input() pathLs: IPathL[][] = [];

a local storage service

import { Injectable } from '@angular/core';
import { IPathL } from './paths.model';

@Injectable()
export class PathsLocalStorageService {
  constructor() {}

  // not required but to make getPaths faster implemented cache
  private cachePathLs: IPathL[][] | null = null;
  private initialValue = [
    [
      { lat: 43.51270075713179, lng: 16.468134790981548 },
      { lat: 43.51205153579524, lng: 16.46757689150645 },
      { lat: 43.5119745090715, lng: 16.466895610416667 },
      { lat: 43.51273927004248, lng: 16.466659576023357 },
      { lat: 43.51284380496191, lng: 16.467753917301433 },
    ],
  ];

  getPaths(): IPathL[][] {
    // if defined return cached value
    if (this.cachePathLs) {
      return this.cachePathLs;
    }

    // get pathLs from local storage
    let pStrOrNull = localStorage.getItem('pathsLs');

    if (pStrOrNull == null) {
      // if no stored value provide following initial value
      return this.initialValue;
    } else {
      // otherwise get from local storage
      let pathLs = JSON.parse(localStorage.getItem('pathsLs')) as IPathL[][];
      // save within app
      this.cachePathLs = pathLs;

      return pathLs;
    }
  }

  setPaths(pathLs: IPathL[][]): void {
    localStorage.setItem('pathsLs', JSON.stringify(pathLs));
  }

  addPath(pathL: IPathL[]): IPathL[][] {
    let pathLs = this.getPaths();
    // add path
    pathLs.push(pathL);

    // save within app
    this.cachePathLs = pathLs;

    // save to local storage
    this.setPaths(pathLs);

    return pathLs;
  }

  resetPaths(): IPathL[][] {
    this.setPaths(this.initialValue);
    this.cachePathLs = this.initialValue;
    return this.initialValue;
  }
}

Obviously API of service can be changed to Observables and a server interaction. In fact the first step to do this is often to mock the service via local storage first (as below), change how any components use the service and then replace the service to a server interaction.

import { of } from 'rxjs'
...
@Injectable()
export class PathsLocalStorageService {
  ...etc
  resetPaths(): Observable<IPathL[][]> {
    this.setPaths(this.initialValue);
    this.cachePathLs = this.initialValue;
    return of(this.initialValue);
  }
}

Answered By – Andrew Allen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0


What is Angular?

Angular is an open-source, JavaScript outline written in TypeScript. Google keeps up with it, and its basic role is to foster single-page activities. As an edge, Angular enjoys clear benefits while likewise outfitting a standard design for formulators to work with. It empowers stoners to deliver huge tasks in a viable way. textures overall lift web improvement viability and execution by outfitting an agreeable construction so that formulators do n't need to continue to modify regulation from scratch. textures are efficient devices that offer formulators a large group of extra elements that can be added to programming easily.

However, is JavaScript ideal for creating single-sprinter activities that bear particularity, testability, and trend-setter efficiency? maybe not.

JavaScript is the most by and large utilized client-side prearranging language. It's composed into HTML reports to empower relations with web sprinters in endless extraordinary ways. As a genuinely simple to-learn language with inescapable help, creating current operations is appropriate.

Nowadays, we have various textures and libraries intended to give essential outcomes. As for front end web advancement, Angular addresses incalculable, while possibly not all, of the issues formulators face while utilizing JavaScript all alone.
Who we are?

We are team of software engineers in multiple domains like Programming and coding, Fundamentals of computer science, Design and architecture, Algorithms and data structures, Information analysis, Debugging software and Testing software. We are working on Systems developer and application developer. We are curious, methodical, rational, analytical, and logical. Some of us are also conventional, meaning we're conscientious and conservative.

Answer collected from stackoverflow and other sources, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0