Storing data from a service into an array in Angular: Best practices

I have a service that provides getter and setter methods, returning id: number and title: String values from my dialog component. I am trying to save these responses into my data array but struggling to achieve it.

For instance:


    0: {id: 0, title: "UK",…}
    1: {id: 1, title: "Usd",…}
    2: {id: 2, title: "ff",…}
    3: {id: 3, title: "yy",…}
    4: {id: 4, title: "nn",…}
    5: {id: 5, title: "mh",…}
    6: {id: 6, title: "tr",…}
    7: {id: 7, title: "es",…}

I would greatly appreciate any assistance in resolving this issue.

This is what I currently have:

app.component.ts

export class AppComponent {
  clickEventSubscription: Subscription

  ngOnInit() {
  }

  id: number;
  title: String;
  data: any = [];

  constructor(private share: ShareDataService) {
    this.clickEventSubscription = this.share.getClickEvent().subscribe(() => {
      this.initialize();
    })
  }

  initialize() {
    this.id = this.share.getId();
    this.title = this.share.getTitle();
    console.log(this.id, this.title);
  }
}

app.component.html

<app-dialog></app-dialog>
<h2>Add values of my service into array:</h2>
<button (click)="initialize()"></button>

share-data.service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ShareDataService {

  title: String;
  id: number;

  getId() {
    return this.id
  }

  getTitle() {
    return this.title;
  }

  private subject = new Subject<any>();

  sendClickEvent() {
    this.subject.next();
  }

  getClickEvent(): Observable<any> {
    return this.subject.asObservable();
  }

}

Thank you very much!

Answer №1

From my understanding of your query, there are multiple approaches to address this issue. However, the most straightforward method is to create a new object each time the initialize method is triggered, as demonstrated below:

Rather than

initialize() {

    this.id = this.share.getId();
    this.title = this.share.getTitle();
    console.log(this.id, this.title);

 }

You should update it to the following:

initialize(): void {

    this.id = this.share.getId();
    this.title = this.share.getTitle();

    const newData = {
      id: this.id,
      title: this.title
    };

    this.data.push(newData);
 }

There seem to be syntax errors and sequencing problems in both your service and app component code that need to be addressed (depending on the version of angular you are using).

Additionally, ensure that instance fields are declared before the instance method declarations within the class/interface.

Move the following snippet to the beginning of your class in share-data.service.ts

private subject = new Subject<any>();

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

Utilizing React and TypeScript: Passing Arguments to MouseEventHandler Type Event Handlers

Can you help me understand how to properly define the event handler handleStatus as type MouseEventHandler, in order to pass an additional argument of type Todo to the function? interface TodoProps { todos: Array<Todos> handleStatus: Mous ...

Angular 9 does not include the mat-radio-group component within its known modules

After upgrading from Angular 2 to Angular 9, I encountered the following error: src/app/contact-list/contact-list.component.html:7:5 - error NG8001: 'mat-radio-group' is not a known element: 1. If 'mat-radio-group' is an Angular compo ...

Dealing with observable errors in Angular 2 beta.12 and RxJS 5 beta.3

Greetings, Currently, I am working with Angular2 beta 12 within VS2015. Upon updating from rxjs version 5.0.0-beta.2 to beta.3, I started encountering several exceptions primarily related to promises. For instance: The property map is not present in th ...

Capturing a center mouse click event in a directive for Angular 6

I created a unique custom directive where I aim to capture middle mouse button click events. Initially, I thought it would be a straightforward process by setting the normal click event and working from there. However, I noticed that it only triggers when ...

What method is the easiest for incorporating vue.js typings into a preexisting TypeScript file?

I currently have a functional ASP.NET website where I'm utilizing Typescript and everything is running smoothly. If I decide to incorporate jQuery, all it takes is running npm install @types/jQuery, and suddenly I have access to jQuery in my .ts file ...

Using opening and closing curly braces within a PHP foreach loop

I am facing an issue with formatting an array in PHP. The array structure is as follows: Array ( [0] => Array ( [team1_score] => 10 [team2_score] => 5 [round_number] => 1 [teamtitle1] ...

Exploring Deeply Nested Routing in Angular

I've been exploring the use of multiple router outlets and encountered an issue. When using the navigateBy function of the router, I am unable to view my child route and encounter an error. However, when I access it via the routerLink in HTML, I get ...

Leveraging both the spread operator and optional fields can improve the productivity and readability of your

Imagine you have an object with a mandatory field that cannot be null: interface MyTypeMandatory { value: number; } Now, you want to update this object using fields from another object, but this time with an optional field: interface MyTypeOptional ...

Displaying related objects information from a single object in AngularFire2 can be achieved by following these steps

As a newcomer to Angular and Firebase, I apologize if my question seems basic. I'm seeking guidance on how to display related object information from one object in angularfire2. Specifically, I want to show the role names assigned to a user. Here is ...

The property is accessed prior to being initialized

In my code, I have a class defined as follows : export class Group { id: string; name: string = ''; type: 'local' | 'ldap' = 'local'; members: number[] = []; This class is being used in my applicatio ...

Guide on making a comma-separated string from an associative array's keys and values

Looking for a fast method, possibly using a built-in PHP function, to generate a comma-separated string from an associative array's key-value pairs. For instance, I would like the following: (array) ['key' => 'value', 'fo ...

Tabs justified are not constrained by width

Utilizing Bootstrap 3, I aim to have the Tabs align perfectly with the full content. The use of nav-tabs can be observed in the code below. It may seem a bit unusual due to my implementation of Angular 4 and the code being copied from Dev Tools. <ul cl ...

The first element of the JSONArray in Android is not a JSONObject

I am currently working on an Android project and I have encountered a JSON parsing issue. I have validated my JSON using JSONLint.com and it seems to be correct. { "traces": [ "{\"lat\": \"42.842097\", \"lng\": &b ...

Attempting to integrate the Angular2 module text-mask-addon into the project

Currently, I am in the process of integrating text-mask-addons into my Angular application. You can find more information at https://github.com/text-mask/text-mask/tree/master/addons Despite attempting to follow the npm links suggestion, I am encountering ...

Combining functions does not result in a callable function, even when the parameters fulfill the constraints of each individual function

I have encountered an issue while trying to compile a Typescript snippet: function foo(v: string) { return 'foo'; } function bar(v: string | number) { return 'bar'; } const notCallable: typeof foo | typeof bar = function() {} as any; ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Utilizing Angular2 Guard to Ensure False IdentityServer4 OIDC Security

After successfully authenticating a user and redirecting them back to the main site, the following code runs: <script src="https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.2.2/oidc-client.min.js"></script> <h1 id="waiting">Waiting... ...

The installation process was unsuccessful due to an error in the postinstall script for [email protected]

While attempting to run npm install, an error message is displayed: Failed at the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38d8c8786ce90829090a3d7cdd6cdd3">[email protected]</a> postinstall script. I hav ...

Exploring ag-Grid: Best Practices for Unit Testing ICellRendererAngularComp Components

I have developed a custom control that utilizes ICellRendererAngularComp from ag-grid with a series of actions and incorporated it into my main ag-grid component. However, I am unsure about how to write tests for this custom control in order to mock the pa ...

What is the method for referencing variables in a JSON response?

Utilizing the Steam API, I made a call to retrieve a response and then formatted it using the paned code: $url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.$key.'&steamids='.$id; $json = json_decode(fi ...