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

Comparing Java Serialization to XML

I am intrigued by the analysis of object form transmission between clients and servers in networking. I would like to explore the criteria for choosing between XML and Java serialization. Which option is best for transforming objects over a network? Why ...

Encountering difficulties importing an NPM library into StackBlitz

Hey there, I'm currently attempting to replicate an Angular example online but am encountering issues importing my Tabulator Library in stackblitz. I keep receiving an error when trying to import it in the hello component. import Tabulator from &apo ...

What is the mechanism through which ng-bootstrap incorporates the NgbRadioGroup and NgbButtonLabel into their NgbRadio directive in Angular 2?

Below is the code snippet for label: import {Directive} from '@angular/core'; @Directive({ selector: '[ngbButtonLabel]', host: {'[class.btn]': 'true', '[class.active]': 'active', &apos ...

Is it possible to align the radio-button label above the radio-button in Angular Material 2?

Currently, I am utilizing angular material 2 (material.io) and attempting to position the label of the md-radio-button above the radio button itself. Here's an illustration: View Radio Buttons The official documentation mentions that you can easily ...

Steps for saving data to a JSON file in a React application

Looking to update a json file with some data. The current contents of the JSON file are: [{"name":"Flossi","image":"https://robohash.org/istevelitut.png?size=50x50&set=set1","price":49,"info": ...

How can I retrieve an SQL query result in JSON format using Ajax?

Similar Question: JSON encode MySQL results In this scenario, the use of Mysql fetch array method is employed to showcase the output. The question that arises here is how one can replace these tags by utilizing JSON encoding. Attempting to retrieve a ...

module 'next/router' cannot be located or its associated type declarations are missing

Running into some issues with my NextJS application. An unusual error message is appearing, even though my code is functioning smoothly without any errors. import { useRouter } from 'next/router'; // Cannot find module 'next/router' or ...

Passing dynamically loaded parameters to a function during dropdown value selection in Angular 2

Could you please review if I am passing the parameters correctly in the li tag's click function of the updateId method? The console errors only point to that line. This is my app.component.html code: <div class='form-group' style="width ...

Angular Drag and Drop with Multiple Items (ng2-dragula)

Currently searching for a drag and drop library that can handle multiple drag capabilities. Unfortunately, none have been found specifically for Angular 2+. While ng2-dragula does meet some of our requirements, it falls short when it comes to supporting ...

Tips for saving the JSON data from a directive so it can be accessed on a different HTML page using Angular

One of my requirements is to retrieve data from an Excel file located anywhere and display it on a separate HTML page. Initially, I managed to display data from multiple sheets on the same page. Now, however, I need to select the file on the first page and ...

"Is the manner in which data is retrieved for a ListView dependent on the individual user

Seeking assistance on filtering data from a MySQL database in a ListView based on the logged-in user. The JSON response from the server is as follows: {"android":[{"username":"lokesh","company":"ffff","client":"xyz","client_no":"5487968475","callback":"20 ...

Unlocking the power of global JavaScript variables within an Angular 2 component

Below, you will find a global JavaScript variable that is defined. Note that @Url is an ASP.Net MVC html helper and it will be converted to a string value: <script> var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)'; Sy ...

Retrieve the output from PHP in JSON format and then utilize jQuery to parse it

I am currently working on a jQuery function $.post(file.php), where the data is being sent to "file.php" and returned in JSON format using json_encode(). Although I am able to successfully retrieve the result, I am unsure how to separate the individual i ...

Leveraging JOLT for partitioning an array depending on an attribute

I'm currently working on using JOLT to split an array into multiple arrays based on an attribute. Although I've attempted the JOLT "Shift" spec, I haven't been successful. I've gone through several resources that demonstrate array tran ...

Struggling to decode JSON in Swift 4

After searching online for a solution as a novice in Swift, I couldn't find any helpful information. I encountered an error while trying to decode my JSON file. Below is the code snippet: import UIKit struct Station: Decodable { let ID: Int ...

Error: Angular2 RC5 | Router unable to find any matching routes

I am currently encountering an issue with my setup using Angular 2 - RC5 and router 3.0.0 RC1. Despite searching for a solution, I have not been able to find one that resolves the problem. Within my component structure, I have a "BasicContentComponent" whi ...

Trouble encountered while using useRef in TypeScript

I'm encountering an issue with the code below; App.tsx export default function App() { const [canvasRef, canvasWidth, canvasHeight] = useCanvas(); return ( <div> <canvas ref={canvasRef} /> </div> ) ...

Firebase authentication link for email sign-in in Angularfire is invalid

Currently, I am utilizing the signInWithEmailLink wrapper from AngularFire for Firebase authentication. Despite providing a valid email address and return URL as arguments, an error is being thrown stating "Invalid email link!" without even initiating any ...

Updating a company's database using the application is successful, but encountering failures during the testing phase

Version Spring 1.3.5 I have thoroughly checked and confirmed that the JSON data sent through Postman is identical to the JSON data generated during testing. Updating the entity using Postman is successful, but updating it via mockMvc fails. Initially, I e ...

I am having trouble getting my angular library published successfully

I'm facing an issue while trying to publish my angular package. I keep encountering this error. https://i.stack.imgur.com/nhYMY.png Here is a screenshot of my package.json file https://i.stack.imgur.com/mWsin.png. ...