Exploring the complexities of cyclic dependencies and deserialization in Angular

I have encountered an issue with deserializing JSON objects in my Angular project. After receiving data through httpClient, I realized that I need to deserialize it properly in order to work with it effectively. I came across a valuable resource on Stack Overflow that explains how to recursively initialize classes using httpClient: How to recursively init class get by httpclient.

Fortunately, I found a solution in the form of the "class-transformer" project, which helped me successfully deserialize all my models. Here is an example of how I implemented this in my services:

public fetchData(data: any): Observable<Result> {
    const formData = new FormData();
    formData.append('data', JSON.stringify(data));
    return this.http.post<Result>('/my/url',
        formData, {
        withCredentials: true
    }).pipe(first(),
        map(response => {
            return plainToClass(Result, response);
        })
    );
}

Additionally, here is how I structured my models using the "class-transformer" library:

// Result.model.ts
import { Type } from 'class-transformer';
import { Data } from './Data.model';

export class Result {

    @Type(() => Data)
    data: Data[]

}
// Data.model.ts
import { Type } from 'class-transformer';
import { Result } from './Result.model';


export class Data {

    @Type(() => Result)
    result: Result[]

}

However, during compilation, I encountered a common error known as "Circular dependency" due to the interdependence between these models. Despite attempting to resolve this issue by using a Barrel (as suggested here), I was unable to fully eliminate the cyclic dependency.

It is essential for me to maintain this specific relationship structure in my models due to constraints imposed by the backend server and data retrieved via httpClient. If you have any insights or solutions on how to address the cyclic dependency problem effectively, please share them!

Answer №1

After some troubleshooting, I decided to implement the barrel solution. It seems that my code was directly importing class A in multiple places, so I refactored them to use the barrel approach, which fixed the issue (although I still receive warnings).

// C.model.ts

// the problem is here
import { A } from './bla/A.model';


export class C {

}
// C.model.ts

import { A } from './bla';

export class C {

}

Additionally, within the ./bla directory, there is an index.ts file that consolidates all model exports.

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

Resolving search box setup problem in PrimeNG dataView

I am working on integrating p-dataView with Angular 5 but encountering an error Cannot read property 'split' of undefined at DataView.filter Despite checking the documentation, I have been unable to find a solution to this issue. It seems lik ...

Discovering relevant information in a JSON file using user-input in Python

I have a JSON file located at this link: https://pastebin.com/2Z2DZ4Y6. My goal is to create a function that allows users to input search terms for tags and retrieve the corresponding gfyId from the JSON data. Although I've made some progress with the ...

Guide to sending a similar request as a curl command through a JavaScript file

After reviewing this Stack Overflow post titled "JavaScript post request like a form submit", I came across a similar situation. Currently, I have a curl command that performs as expected: curl -v -X POST -H "application/json" -H "Content-type: applicatio ...

The 'Headers' type does not share any properties with the 'RequestOptionsArgs' type

I have included the necessary headers, objects, and URLs in my code but I keep getting an error message. The 'Headers' type does not have any properties in common with the 'RequestOptionsArgs' type This is my code: getContactData(a ...

What seems to be the issue with this json.load function call?

I wrote the following Python 3 code snippet: import json with open('calldb.json', 'r') as G: data = json.load(G) print(data) Accompanied by this JSON file: [ { "n": { "identity": 0, "labels": [ ...

Even if I set a small modal, the large one can still be visible in the background

I've been working on a small modal, but encountered an issue where the large modal remains visible in the background when the small one is displayed. Any suggestions on how to fix this? I made some updates to my code based on recommendations. Here is ...

Show information retrieved from fetch api

Hi there! I've been trying to fetch data from the Avascan API and display it on my HTML page, but so far, I haven't had any luck. I've experimented with using the Fetch API, JSON, and AJAX methods, but none of them seem to work for me. Do yo ...

PHP is unable to fetch JSON data from an ajax request

My JavaScript code is as follows: var person = []; person[0] = "John"; person[1] = "Doe"; person[2] = 46; var myData = JSON.stringify(person); $.ajax({ type: "POST", url: "test.php", dataType : "text", ...

Using v-for with nested objects

Have you been attempting to create a v-for loop on the child elements of the {song: "xxx"} object within the songs array? export const data = [ {id: "1", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : &apos ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Guide to parsing the HTML structure of a webpage from a different domain

Struggling with parsing the DOM of a remote webpage using AJAX. Can't find any examples or tutorials on this process. My goal is to navigate through the DOM of a remote page, locate a tag with a specific id/class, extract the content within that tag, ...

Why does this particular check continue to generate an error, despite my prior validation to confirm its undefined status?

After making an AJAX call, I passed a collection of JSON objects. Among the datasets I received, some include the field C while others do not. Whenever I try to execute the following code snippet, it causes the system to crash. I attempted using both und ...

Converting basic text into JSON using Node.js

Today I am trying to convert a text into JSON data. For example: 1 kokoa#0368's Discord Profile Avatar kokoa#0000 826 2 Azzky 陈东晓#7475's Discord Profile Avatar Azzky 陈东晓#0000 703 3 StarKleey 帅哥#6163's Di ...

Utilizing getters and setters with v-model in a class-based component: A step-by-step guide

Transitioning from an angular background to vuejs has been challenging for me as a newbie. I've encountered issues while trying to bind setter/getter in v-model for an input field. Interestingly, when I directly bind it to a variable, everything works ...

Spring Boot receiving null values from Angular form submission

I am currently working on a form in Angular that is used to submit information such as author, context, and recently added images. However, I have run into an issue where I am able to successfully retrieve the author and context, but not the images (it alw ...

Creating a React component in Typescript to utilize lodash helper functions

I have a component that looks like this: import React, { Component } from 'react'; import throttle from 'lodash.throttle'; interface Props { withScroll: boolean; } class Image extends Component<Props, {}> { throttledWindowS ...

Having trouble decoding a JSON string with slashes?

Can someone shed some light on the reason behind this phenomenon? var_dump(json_decode(stripslashes(json_encode(array("O'Reiley"))))); // array(1) { [0]=> string(8) "O'Reiley" } var_dump(json_decode(stripslashes(json_encode(array("O\&ap ...

To efficiently update several rows in a single query, we require input in the form of a JSON object containing multiple sets of data

update users as u set -- postgres FTW email = u2.email, first_name = u2.first_name, last_name = u2.last_name from (values (1, '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c14131010150f3c0b1915111d121 ...

What is the best way to deserialize JSON using RestTemplate when the request body could be a list or an object?

When trying to deserialize JSON from an API, I encountered inconsistency in the JSON body. Sometimes it is presented as a list and other times as a single item. For example: "Charge": [ { "ChargeType": "EXPRESS 12:00", ...

Decoding a JSON string with Python

As a newcomer to parsing JSON strings, I recently utilized json.loads for text analysis but am struggling with isolating only the Titles. The code snippet demonstrates this: from alchemyapi import AlchemyAPI import json alchemyapi = AlchemyAPI() def ru ...