Manipulating data with Angular 2 services: accessing and updating values

This code snippet is all about managing an array in Angular. The Injectable decorator is used to define a service called Svc with methods for setting and getting column definitions.

 import { Injectable } from '@angular/core';

 @Injectable()    
 export class Svc {

     constructor() {}

     private _updatedArray: Array < any > = [];
     setColDefs(columns: any) {
         this._updatedArray.push(columns);
         console.log(columns);
     }
     getColDef() {
         return this._updatedArray;
     }
}

An example of setting the array in one component:

...
this._listSvc.setColDefs(colDefArray);
...

And in another component:

...
import { Svc } from '../services/mySvc.svc'; 

@Component({ 
...
}) 

export class EditComponent implements OnInit, OnDestroy{ 

    constructor( 
        private _editCompSvc: Svc 
    ){} 

    ngOnInit() { 
        console.log(this._editCompSvc.getColDef()); 
    }

The issue reported is that the getColDef function always returns an empty list even though columns were added. Any suggestions or explanations for this behavior would be greatly appreciated. Thank you!

Additional module information:

import { NgModule } from '@angular/core';
import { routing } from './routes/myroute.route';
import { Svc } from './services/mySvc.svc'

import { ListComponent } from './actions/list.comp';
import { EditComponent } from './actions/edit.comp';

@NgModule({
    imports:
    [
        routing
    ],

    declarations:
    [
        ListComponent,
        EditComponent
    ],

    providers:
    [Svc]
})

export class Module { }

Answer №1

It is likely that you are invoking the update function after the ngOnInit of EditComponent

ngOnInit() {  // I'm certain this occurs before the update
   console.log(this._editCompSvc.getColDef()); 
}

Additionally, it is preferable to write the code in this manner:

export class Svc { 

constructor() { } 

private _updatedArray:Array<any> = [];
   set colDefs(columns: any) { 
     this._updatedArray.push(columns); 
     console.log('setting the colDefs',columns); 
   }
   get colDef(){ 
        console.log('getting the colDefs',this._updatedArray); 
     return this._updatedArray; 
   }

To demonstrate, execute the above code and you should observe "setting the colDefs" before retrieving it.

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

Is a loading screen necessary when setting up the Stripe API for the checkout session?

While working on my web app and implementing the Stripe API for creating a checkout session, I encountered an issue where there is a white screen displayed awkwardly when navigating to the Stripe page for payments. The technology stack I am using is NextJ ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

Bringing in a module that enhances a class

While scouring for a method to rotate markers using leaflet.js, I stumbled upon the module leaflet-rotatedmarker. After installing it via npm, I find myself at a loss on how to actually implement it. According to the readme, it simply extends the existing ...

``Should one prioritize the use of Generics over Inheritance, or is there a better way

We are currently in the process of implementing new contracts for our icons system, and we have encountered a debate on which approach is more preferable. Both options result in the same interface: Using Generics -> Although the interface may be less ...

Is it possible to apply two ngClass directives to a single div element in Angular 4?

When I click to start editing, a component is called for the editing process. In this component, I am unable to click on anything and the background turns black, which is okay. However, I would like for each ID that I select to edit to become active with a ...

Tips for creating PrimeNG tables with columns that automatically adjust in size

Is there a way to automatically adjust and resize the columns in my PrimeNG table? I'm looking for a method to make this happen. Can you help me achieve this? ...

Error message: "Cannot access property 'push' of null in Angular FormArray"

Working with Angular Reactive FormArray to dynamically add multiple inputs upon clicking the "Add" button. Encountering an error message stating "Cannot read property 'push' of null" when attempting to add/push input fields. Considering if ther ...

What steps should I take to ensure the successful function of the App Routing system in this scenario?

After creating an Angular App, I encountered a challenge in one of my services. When I call the http.post method and subscribe to it, I aim to redirect to the previous page with a parameter (e.g., "http://localhost:3000/profile/aRandomName"). Unfortunately ...

What is the best way to streamline the creation of a "products filter" using Node.js and Angular?

I have decided to build an angular application for an online computer store, and I am using a node/express backend. One of the key features of the application is the products page, where users can view all the products available in our database. Each produ ...

Transferring an array of data across different screens within an Ionic 2 application

I am a newcomer to Ionic 2 and I am encountering difficulties when it comes to passing data between pages. Within my Home.ts file, there exists a global array containing certain numbers that have been calculated. My intention is to transfer this array to m ...

"Enhance your PrimeVue Tree component with interactive action buttons placed on every TreeNode

Details: Using Vue 3.3.6 in composition API script setup style Utilizing PrimeVue 3.37.0 and PrimeFlex 3.3.1 Implemented with Typescript Objective: To create a tree structure with checkboxes that are selectable, along with action buttons on each TreeNod ...

The attempt to combine an array of elements with another array using FieldValue.arrayUnion() in Firestore was unsuccessful

My cloud function is triggered when a specific event occurs. Within the function, I receive an array of strings like this example: let h:string[] = ["foo","bar","baz"]. When I attempt to update an array field within my document using names: admin.firestor ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

Encountering a problem when utilizing window.ethereum in Next Js paired with ether JS

Experiencing some difficulties while utilizing the window.ethereum in the latest version of NextJs. Everything was functioning smoothly with NextJs 12, but after upgrading to NextJs 13, this error started popping up. Are there any alternative solutions ava ...

Distinguishing between TypeScript versions 2.0.x and 2.1.x using type definitions and filtering with a switch/case statement

@ngrx/store (an observable redux implementation for angular (2) ) utilizes a specific pattern to assign the correct type to a reducer. Check out the actual code here. export const ActionTypes = { FOO: type('foo'), BAR: type('bar&apos ...

In a specific Angular project, the forget password feature is experiencing issues with sending email links in the Chrome browser. Interestingly, this issue only occurs the first

I'm currently working on an Angular 6 application that has been deployed with the domain "www.mydomain.com/". All the routes are functioning properly, such as "www.mydomain.com/dashboard" and "www.mydomain.com/products". However, there is an issue w ...

When downloading text using Angular, the file may not display new line characters correctly when opened in Notepad

When downloading text data as a .txt file in my Angular application using JavaScript code, I encountered an issue. Below is the code snippet: function download_text_as_file(data: string) { var element = document.createElement('a') eleme ...

Setting up Angular Toolkit via npm installation

After successfully installing the UIKit npm package within an Angular 2 CLI project, what steps should I take to utilize it? I have also installed typings for UIKit (@types/uikit), but I am unsure of how to properly import the package into a controller i ...

Encountering a issue while running npm start with Angular 2 RC build

After upgrading from Angular2 beta 15 to the RC version, I encountered some errors while trying to run my application. typings/browser/ambient/es6-shim/index.d.ts(8,14): error TS2300: Duplicate identifier 'PropertyKey'. typings/browser/ambient/e ...

Creating specialized validation for numeric fields in Angular2

Attempting to implement custom validation in Angular 2 has been a challenge for me. I have followed the necessary steps based on my understanding, but still struggling to get it working. import { FORM_DIRECTIVES, AbstractControl, ControlGroup ,FormBuilder ...