Transforming JSON data into an Angular TypeScript object

Delving into the realm of Angular on my own has been quite an enlightening journey, but I'm currently facing a specific issue: My aim is to create a website using both Spring for the back end and Angular 7 for the front end.

However, I've encountered a roadblock.

At present, I have three entities: Builder, Category, and Ship.

Naturally, my ship entity includes attributes such as the builder of the ship and its category (e.g. hunter).

Upon making a request to my service (Vaisseau.service.ts), he hands me JSON:

{
  "_embedded" : {
    "vaisseaus" : [ {
      "nom" : "nomVaisseau",
      "description" : "Description du vaisseau",
      "image" : "http://127.0.0.1/img/Vaisseaux/2.jpg",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/vaisseaus/2"
        },
        "vaisseau" : {
          "href" : "http://localhost:8080/vaisseaus/2"
        },
        "constructeur" : {
          "href" : "http://localhost:8080/vaisseaus/2/constructeur"
        },
        "categorie" : {
          "href" : "http://localhost:8080/vaisseaus/2/categorie"
        },
        "utilisateurs" : {
          "href" : "http://localhost:8080/vaisseaus/2/utilisateurs"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/vaisseaus{&sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/vaisseaus"
    },
    "search" : {
      "href" : "http://localhost:8080/vaisseaus/search"
    }
  },
  "page" : {
    "size" : 5,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

The following function encapsulates this :

public constructeurs: any;
  public pages: Array<number>;
  private currentPage = 0;
  private size = 2;
  private totalPages: number;
  private currentKeyword = '';

  constructor(private constService: ConstructeurService, private router: Router) {
  }

  ngOnInit() {
    this.onGetConstructeurs();
  }

  onGetConstructeurs() {
    this.constService.getConstructeurs(this.currentPage, this.size)
      .subscribe(data => {
        this.constructeurs = data;
        this.totalPages = data['page'].totalPages;
        this.pages = new Array<number>(this.totalPages);
      }, err => {
        console.log(err);
      });
  }

In my template file, there's a snippet that displays vessels, but unfortunately, an error pops up:

ERROR TypeError: "_v.context.$implicit.constructeur is undefined"
    View_LstVaisseauComponent_3 LstVaisseauComponent.html:35
    Angular 29
    RxJS 5
    Angular 9
LstVaisseauComponent.html:34:56
    View_LstVaisseauComponent_3 LstVaisseauComponent.html:34
    Angular 15
    RxJS 5
    Angular 9

This error prevents me from accessing the ship's builder and category information.... With the included JSON:

"vaisseau" : {
          "href" : "http://localhost:8080/vaisseaus/2"
        }

I've scoured Google in search of various methods to parse the JSON (interfaces in Angular, or constructors that take JSON arrays as parameters...)

I can't seem to pinpoint the source of my issue... Is it on the backend where I need to tweak parameters for my REST API to always return all data instead of just links pointing to entities? Or perhaps in Angular where I should handle loading different objects from these links?

Despite following numerous online tutorials, I'm still unsure about the most efficient way to tackle this JSON data - Interfaces, Mappers, or other approaches...

Answer №1

To enhance your code, consider incorporating observer response in the following manner:

  public retrieveSpacecrafts(page: number, size: number) {
    return this.httpClient.get(this.host + '/spacecrafts?page=' + page + '&size=' + size, {
      observe: 'response'
    });
  } 

If this approach does not work as expected, consult with the developer to ensure that the data returned does not contain any underscore sign within the _embedded field.

Answer №2

Ultimately, I utilized projections to retrieve the desired data in a more efficient manner. The use of JSON format is a result of Spring HATEOAS, which opts for sending links instead of sub-entities. Various solutions can be found online to navigate this "issue", but personally, I have chosen to employ projections. For those interested, here's a brief example:

 @Projection(name = "vaisseauProjection", types = Vaisseau.class)
public interface VaisseauProjection {

    public long getId();
    public String getNom();
    public String getDescription();
    public String getImage();
    public Constructeur getConstructeur();
    public Categorie getCategorie();

}

Frontend :

  public getVaisseauxByKeyword(mc: string, sort: string, order: string, page: number, size: number): Observable<PageableVaisseaux> {
    return this.httpClient.get<PageableVaisseaux>(this.host + '/vaisseaus/search/byNomPage?mc=' + mc + '&sort=' + sort + ','
      + order + '&page=' + page + '&size=' + size + '&projection=vaisseauProjection');
  }

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

Node.js: Handling Undefined Request Parameters

My get route is set up to receive two parameters "limit" and "page". router.get('/:limit/:page', userController.list); class UserController{ public list(req:Request, res:Response): void{ const limit:number = +req.params.limit || 25; ...

Issue Encountered with FabricJS: Unable to Execute 'drawImage' with Image Subclass

I'm working on a project that requires me to add images of different types to a canvas, save them as JSON, and then load them again. The unique property needed for each type is simply the differentiation in type. To achieve this, I have created a new ...

Angular2 has encountered a malfunction with the chart feature

My attempt to create a Bar Chart with this GitHub repository is not working in Chrome. You can view my code on Plunker. Can someone help me identify the issue? Below is the updated code: app.ts import {Component, Pipe, PipeTransform} from 'angular2 ...

Using Typescript to retrieve the Return Type of a function when called with specific Parameter types

My goal is to create 2 interfaces for accessing the database: dao can be used by both admins and regular users, so each function needs an isAdmin:boolean parameter (e.g. updateUser(isAdmin: boolean, returnUser)) daoAsAdmin, on the other hand, allows metho ...

Handle the Axios response for a POST request, specifically capturing the JSON data when a 400 (Bad Request) error

When making an http request in an api using React Native with Axios, I am able to retrieve and parse json data when the callback is 200. However, in cases where I call a method - such as registering a user with an email that is already registered - I recei ...

The DataGrid is only displaying a single result instead of multiple results

I'm having difficulty displaying all the results in this MUI data table. Currently, it is only showing one result instead of all, and I can't figure out what I'm doing wrong. If you have any suggestions or best practices on how to properly ...

How can one click the button within the expanded dropdown while hovering over the navigation item in Angular and Bootstrap?

Issue Description: Upon hovering over a navigation item, the dropdown container is displayed but it's not clickable. Desired Behavior: Hovering over a navigation item should display the dropdown container and allow clicking on its contents. Furthermo ...

Creating JSON in Python by combining data from two lists of lists involves merging the elements from both lists into a single JSON format

Having two csv files(semi-colon delimited) with the structure and sample data below: File 1: qid;question 1.0;How can I find specific content 2.0;How do I modify content 2.0;How can I edit items 2.0;I need to change some answers 3.0;How do I troubleshoot ...

Angular 2 - Karma is having trouble locating the external template or style file

The file structure for this project (taken from the Angular 2 official site) is as follows: https://i.stack.imgur.com/A6u58.png Upon starting Karma, I encountered errors indicating that two files were not found under /@angular/... To resolve this issue, ...

Warning: Unresolved promise: NullInjectorError encountered: StaticInjectorError(AppModule) when trying to use FormBuilder

I encountered an error in my Angular app when adding routes in gifts-routing.module.ts. The error disappears when I remove the routes, but I still need to implement routing. How can I resolve this issue? ERROR Error: Uncaught (in promise): NullInjectorErr ...

Angular Issues: Problems with Saving Data to Local Storage

Encountering 2 bugs in the methods responsible for saving products to local storage when users add them to their 'favorites' list. The code pertains to an Angular service but can be understood independently of this framework. Bug #1: Occasional ...

"Executing a SQL command that involves a JSON data type column

Currently, I am dealing with a table called individual customer that contains a column named employmentDetails which stores data in JSON format. My objective is to retrieve customers who have an empty locality field. [{ "employmentStatus": " ...

Type 'Partial' cannot be assigned a value when combining interfaces with generic types

Consider the following scenario: class Table<ValuesType extends DefaultTableValues = DefaultTableValues>{ public values: ValuesType; constructor(initialValues:ValuesType) { this.values=initialValues; } public set(newValues:Pa ...

Is CORS necessary when using npm, and is Putty a viable tool for web application development?

Currently, I am immersed in a web application project that relies on the following technologies: Express.js + Node.js MySQL Angular 4 PM2 (Process manager) Here are the libraries utilized on the backend: express body-parser jsonwebtoken bcrypt-nodejs ...

A step-by-step guide on uploading images to Firebase using Ionic 4

I'm having trouble uploading images to Firebase. Can anyone offer assistance? Does anyone know how to upload images to Firebase in Ionic 4.0? The code below used to work in Ionic 2, but now there's a delay of about 30 seconds after clicking the ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

There was a JSON Parsing error because the JSON array had no value assigned to it

Need help with a code that requires passing a static user ID for authentication, fetching JSON response from a URL, and displaying it in a listview. However, encountering an error "JSON Parsing error: No value in (JSON array)". Any assistance would be ap ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

Creating a csproj file for an existing project in Angular: A step-by-step guide

I recently utilized the Angular CLI (version 12) to initiate my Angular project, but I noticed that the csproj file is missing. Is there a method to generate the csproj without compromising any of the existing files? Any help would be greatly appreciated ...