Search code examples
jsonangulartypescriptclass-transformer

Deserialize and cyclic dependencies in Angular


I have several model.ts files. When I use httpClient, I get a JSON object, but it does not work correctly since I have to deserialize them: How to recursively init class get by httpclient.

BUT since so, I found the project "class-transformer" that help me deserialize all my models. I have in my services:

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

And for models something like:

// A.model.ts
import { Type } from 'class-transformer';
import { B } from './B.model';

export class A {

    // Some properties
    @Type(() => B)
    b: B[]

    // Some methods
}

And B

// B.model.ts
import { Type } from 'class-transformer';
import { A } from './A.model';


export class B {

    // Some properties
    @Type(() => A)
    a: A[]

    // Some methods
}

But, when compiling I got "Circular dependency" and indeed there is a circular dependency...

Looking for solution I understant that I can use a Barrel (https://github.com/typestack/class-transformer/issues/230) but it did not work. My only constraint is that I have to keep this relation -> (or something really similar since I can not modify the backend and so data I will receive with httpClient).

Any idea on how to fix the cyclic dependency?


Solution

  • Finally, I used the barrel solution. It appears that in the rest of my code there were import of class A directly, I changed them to use the barrel and everything works (I still have warnings. But it works)

    // 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 {
    
    }
    

    And at ./bla I have a index.ts with all the model export