Angular 2: Creating a Reusable Object for Uniform JSON Structures

I am facing an issue with JSON data as I have 3 tables in my database named "dictionary" with the same structure but different column names:

{"id":1,"test_1":"test"},{"id":2,"test_1":"lalala"} - first JSON 


{"id":1,"test_2":"****"},{"id":2,"test_2":"afery-t"} - second JSON

I aim to create a single Class in Angular 2

 export class dictionary{

   id:number;
   dictValue:string;

}

Is it feasible to convert these different JSON objects into one like this, because this current method is not functioning:

res => <dictionary[]>  res.json()

Furthermore, in the HTML template, I am getting JSON object instead of class values in NgFor.

 <tr *ngFor="let item of directoryArray">
{{item.test_1}} - I desire {{item.dictValue}}
</tr>

controller

 directoryArray:dictionary[];
this._httpService.getAll().subscribe(
            data => this.directoryArray = data,
            error => alert(error),
            () => console.log("Done"));

Thank you for your assistance. Can you please let me know if it is possible or if I need to modify values in the database or create different objects for each JSON?

Answer №1

To implement this functionality, it is recommended to utilize an Interface:

export interface Dictionary { // Suggesting the use of 'Dictionary' here
   id: number;
   dictValue: string;
}

If you are unsure about how your getAll function is structured, here is an example demonstrating how to retrieve the initial JSON data:

getFirstJSON(): Observable<Dictionary[]> {
  return this.http.get('the Url')
    .map(res => res.json().map((x:any) => Object.assign({id:x.id,dictValue:x.test_1}))
}

In the code snippet above, we are using the map function to align the properties with your specified interface.

Subsequently, within your component file:

directoryArray: Dictionary[];

this.service.getFirstJSON()
  .subscribe(data => {
    this.directoryArray = data;
  })

Now that the properties adhere to the defined interface, they can be utilized in the template as follows:

<tr *ngFor="let item of directoryArray">
  <td>{{item.dictValue}}</td>
</tr>

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

Refine the JSON data to only include the values you need

I've been spending a considerable amount of time on this challenge, but I'm facing difficulty in solving it. The issue at hand is that I have a JSON file that I am fetching from a URL, and my objective is to create a filter that displays only nam ...

Using local variables in Angular2 templates

For the specific scenario discussed below, I have assigned the local variable #input to multiple radio buttons. My goal is to select the radio button within the <tr> when it is clicked. Surprisingly, the provided code functions as expected, yet the ...

Utilizing HTML and Ionic 3.x: Implementing a for loop within the HTML file by utilizing "in" instead of "of"

I am working with multiple arrays of objects in my typescript file and I need to simultaneously iterate through them to display their contents in the HTML file. The arrays are always the same size, making it easier to work with. Here is what I currently ha ...

The selectors in NgRx store are failing to retrieve data from the main global store

As I delve into the world of ngrx, I find myself struggling to fully understand and implement it effectively within my application. Recently, I integrated ngrx version 8.3 into my project in hopes of organizing my state management efficiently. My goal is ...

Obtaining a JSON-formatted error log backtrace in Rails

One of the challenges I faced in production was converting my logs output to JSON using lograge. It made it convenient for displaying on various log services like Amazon. config.lograge.enabled = true config.lograge.formatter = Lograge::Formatters::Logs ...

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

Upon implementing a custom adapter and incorporating JSON, the application unexpectedly crashed

An error occurred: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 in spinner public void RetrieveData() { JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener ...

Is it necessary to retrieve the data that was posted from the back-end? Implementation using Angular and Node.js

I need some advice on how to handle worker data in my Angular, NodeJS, and MySQL app. In the FORM, users can add workers whose information is then sent to the backend for processing. The user can preview the posted information and delete workers if needed. ...

Running a TypeScript program that has been compiled with module resolution is not working as expected

I am currently in the process of compiling a TypeScript file with the following code: import { magic } from 'lib/magic'; magic(); The file structure looks like this: ./src/ main.ts lib/ a/magic.ts b/magic.ts Within ...

Guide to incorporating code coverage in React/NextJs using Typescript (create-next-app) and cypress

I initiated a fresh project using create-next-app with the default settings. npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365544535742531b58534e421b57464676070518021801">[email protected]</a> --- Would you l ...

How to delete an item from an object in TypeScript

Can you help with filtering an object in Angular or TypeScript to eliminate objects with empty values, such as removing objects where annualRent === null? Additionally, what method can we use to round a number like 2.833333333333335 to 2.83 and remove the ...

Employ jq to organize keys within a JSON object based on a specific property

Is there a way to sort the keys of a JSON file in natural order while prioritizing keys listed in the 'required' section? The command below sorts keys in natural order: jq --sort-keys . /tmp/source.json > ./tmp/target.json { "Request ...

Is there a way to guide the user to a different page while still inside a getJSON function?

After making an external call to a JSON file, I am facing an issue where if the JSON data is null (possibly due to expired user session), the user should be redirected to the logout.php page. However, in my current implementation, instead of redirecting, t ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

Issue with SvelteKit: PageData not being refreshed in API response after initial render

I am relatively new to working with Svelte and SvelteKit, and I am currently trying to fetch data from an API. I have followed the SvelteKit todo sample code, which works well for the initial rendering and when clicking on an a tag. However, I am facing an ...

What is the best approach: Developing a class or a service to handle multiple interfaces?

My current project involves creating multiple interfaces, and I would like to keep them separate for clarity. Would it be wise to do this in a service or a class? Additionally, is it possible to utilize dependency injection for classes? Thank you for your ...

receiving JSON data in Java RESTful web services using the Jersey framework (javax.ws.rs.*)

I am facing an issue with passing a json contentType to the glassfish server where I have set up a java restful web service. My POST request is coming from Node.js using needle : var options = { json: true, headers: {'Content-Type':&apo ...

Access PDF document in a fresh tab

How can I open a PDF file in a new tab using Angular 6? I have tried the following implementation: Rest controller: @RestController @RequestMapping("/downloads") public class DownloadsController { private static final String EXTERNAL_FILE_PATH = "/U ...

Converting serialized form data to JSON in Node.js

For my project, I am utilizing Angular along with Node.js and Express 4, in addition to socket.io. I have developed a service in my Angular application that sends serialized form data to the server. This service functions similarly to jQuery.serialize(). ...

Trouble arises when applying CSS to ng-x accordion styling

While working with ng-x accordion in Angular 2, I successfully rendered my accordion component. However, I encountered an issue when trying to add styles to the template provided by ng-x accordion. Despite using CSS in my rendered component for classes l ...