Saving JSON data in a variable or array post subscription: What's the preferred method?

I have been receiving JSON files in the following format:

{streetAddress: "Kosterlijand 20", postalCode: "3980", city: "Bunnik", country: "Netherlands"}

Although the length of these files varies, the structure always remains the same:

{key: "string value", key: "string value", etc...}

I have attempted to subscribe and retrieve this data, but I am facing challenges storing it properly. When using the code below:

this.service.getEntityDetails()
    .subscribe(data => console.log(data));

The console displays the JSON data successfully. However, when I try to store the data in different variables as shown here:

public test: any[];
public test1: any[]=[];
public test2: string[];
public test3: string[]=[];
public test4: {};

constructor(service:Service){}
this.service.getEntityDetails()
.subscribe(data => {
    test=data;
    test1=data;
    test2=data;
    test3=data;
    test4=data;

    console.log("test:"+test+", test1: "+test1+", test2: "+test2+", test3: "+test3);
});
}

The output in the console remains the same for all variables.

test:[object Object], test1: [object Object], test2: [object Object], test3: [object Object] test4[object Object]

I aim to manipulate the data similar to how KeyValuePipe works, yet I am unable to achieve this due to my inability to save the values appropriately. Any assistance on resolving this issue would be greatly appreciated.

Further details can be provided upon request.

Answer №1

Let me clarify a few points...

public dataCollection: Array<any> = [];

  this.service.fetchEntityInfo()
    .subscribe(result => {
        dataCollection=result;
    });

There you have it. You have successfully saved the desired value.

If you are really keen on logging your object as a string, you can reference the specific fields like so...

console.log(this.dataCollection[0].specificFieldInYourObject)

Or you could create a function to loop through the keys of your objects. However, since your query was about storing the object, the above method should suffice.

Answer №2

You can improve your code by utilizing the async pipe instead of subscribing in the TypeScript file. Taking inspiration from examples provided by @ak.leimrey and @Fateme Fazli

/** @file app.component.ts */ 

@Component({ /* ... */ })
export class AppComponent  {
    public test$: Observable<any[]>;

    constructor(service: Service) {
       this.test$ = this.service.getEntityDetails();
    }
}

Incorporate the following into your template:

<ng-container *ngIf="(test$ | async) as test">
    <div *ngFor="let item of test | keyvalue">
        {{item.key}}:{{item.value}}
    </div>
</ng-container>

Answer №3

If you need to show data from a database in your application, it must be saved in a component property. Here's an example:

/** @file app.component.ts */ 

@Component({ /* ... */ })
export class AppComponent  {
  public myData: any[];

  constructor(service: Service) {
    this.service
      .getEntityDetails()
      .subscribe(data => {
        this.myData = data;  
        console.log('My data', this.myData);
      });
  }
}

After that, you can display the data like this:

<!-- @file app.component.html -->

<div>{{ myData }}</div>

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

What is the best way to clear the parent component's content from the child component in Angular?

Having an issue with Angular routes. The URLs are functioning properly, but when I navigate to the child component, specifically CreateEventComponent, the parent component's content from EventsComponent is also displayed. How can I make sure that th ...

Displayed even when data is present, the PrimeNg empty message persists

I have set up a PrimeNg table to display data with an empty message template like this: <ng-template pTemplate="emptymessage"> <tr> <td> No records found </td> </tr> </ng-template> ...

Arranging objects in an array based on a separate array of strings

Here is an array of objects that I need to rearrange: var items = [ { key: 'address', value: '1234 Boxwood Lane' }, { key: 'nameAndTitle', value: 'Jane Doe, Manager' }, { key: 'contactEmail', value: ...

Which types of mouse events are compatible with Angular2?

Exploring mouse events in Angular2 has sparked my curiosity. I have implemented the click event, but now I wonder what other mouse events are available, such as mouseover. Where can I find a comprehensive list of mouse events supported by Angular2? The o ...

The issue arises when trying to pass multiple parameters with the Angular 2 router and encountering

After creating a sample Plunker to pass multiple parameters to the next page, I encountered an issue where the crisis center routing failed to work properly upon clicking on items. See the demonstration on Plunker here: http://plnkr.co/edit/ngNSsKBzAuhaP0E ...

What impact do the input values of an Angular reactive form have on the DOM?

I am currently working on developing a UI wizard app using Angular (reactive forms) version 6/7. The main purpose of this app is to enhance the product page of an ecommerce platform such as Shopify or WordPress. I am utilizing angular material radio inputs ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

What is the best way to authenticate an admin in the front-end using backend technologies like Node.js, Angular, and MongoDB?

Within the user model, there is a property named isAdmin with a default value of false. In MongoDB, I have manually created an admin account with the isAdmin property set to true. When logging in as an admin, the program verifies this and displays "admin ...

Trigger the identical event to be sent to two distinct functions upon the corresponding button click in Angular 2 using Typescript

I recently implemented a service that fetches JSON data and subscribes to two different variables within my component. These variables are then used by two separate drop-down lists to filter the data accordingly. The filtered data is then sent to another s ...

Using MUI DatePicker and react-hook-form to implement a date picker in the format DD/MM/YYYY

I have developed a custom datePicker component that combines react-hook-form and Material UI. However, I am encountering an issue where the values are being displayed in the format: "2024-04-10T22:00:00.000Z" Below is the code snippet: import { Localizati ...

Exploring jQuery: Mastering the art of iterating through multi-level arrays

I'm a beginner at using jQuery and I could really use some assistance with this. I made an Ajax call with the success function (data) returning an array like the one below. Now, I need to iterate through this array and perform a specific action for ...

Having trouble retrieving a value from the img.onload event handler. A 'boolean' type error is being thrown, indicating it cannot be assigned to type '(this: GlobalEventHandlers, ev: Event) => any'

In my Angular application, I have implemented a method that verifies the size and dimensions of an image file and returns either false or true based on the validation result. Below is the code snippet for this function: checkFileValidity(file: any, multipl ...

Integration of Sproutcore and Rails for handling many-to-many relationships with JSON

Imagine you have two models in Ruby on Rails - ModelX and ModelY. Now, let's say these models also exist in Sproutcore. They are connected through a many-to-many relationship. In the context of ModelX, we have an attribute called xArray that holds re ...

Leverage the TypeScript compiler's output from a .NET library within a Blazor application by referencing it

I am currently facing an issue with three different levels: Main Issue: I have developed a Blazor WebAssembly (WASM) application that requires JavaScript, but I prefer to use TypeScript. To address this, I have added a tsconfig file and the TypeScript cod ...

Error encountered: GWT RPCManager performTransactionReply- Transaction does not exist

I am currently utilizing SmartGWT -4.0 and attempted to execute the example of utilizing DataSource with Json, RestDataSourceWithJson.zip. However, upon running it, the development mode console showed me the following error: [ ERROR ] [ restdatasourcewi ...

Is it possible to merge these two scripts into a single one within Vue?

As a newcomer to VUE, I am faced with the task of modifying some existing code. Here is my dilemma: Within a single component, there are two script tags present. One of them contains an import for useStore from the vuex library. The other script tag incl ...

Flexible type definition including omission and [key:string]: unknown

When I write code, I like to explain it afterwards: type ExampleType = { a: string; b: boolean; c: () => any; d?: boolean; e?: () => any; [inheritsProps: string]: unknown; // If this ^ line over is removed, TypeNoC would work as expecte ...

Why does WebStorm fail to recognize bigint type when using TSC 3.4.x?

Currently, I am working on the models section of my application and considering switching from using number to bigint for id types. However, despite knowing that this is supported from TSC 3.2.x, WebStorm is indicating an error with Unresolved type bigint. ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

Why is it necessary to use 'then' on the response JSON when using the Fetch API? It's like trying to decipher the hidden meaning

While delving into the realm of promises, I decided to test it out with a basic GET request on Twitch. Yet, one aspect is still puzzling me - why does json() return a promise? The response already contains the data, so what's the deal with it being wr ...