【问题标题】:Deserialize and cyclic dependencies in AngularAngular中的反序列化和循环依赖
【发布时间】:2020-09-04 17:09:11
【问题描述】:

我有几个 model.ts 文件。 当我使用 httpClient 时,我得到一个 JSON 对象,但它不能正常工作,因为我必须反序列化它们:How to recursively init class get by httpclient

但是从那时起,我找到了“class-transformer”项目,它可以帮助我反序列化我的所有模型。 我的服务有:

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);
        })
    );
}

对于类似以下的模型:

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

export class A {

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

    // Some methods
}

和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
}

但是,编译时我得到了“循环依赖”,确实存在循环依赖...

寻找解决方案我知道我可以使用桶 (https://github.com/typestack/class-transformer/issues/230) 但它不起作用。 我唯一的限制是我必须保持这种关系->(或者一些非常相似的东西,因为我无法修改后端,因此我将使用 httpClient 接收数据)。

关于如何修复循环依赖的任何想法?

【问题讨论】:

    标签: json angular typescript class-transformer


    【解决方案1】:

    最后,我使用了桶解决方案。似乎在我的其余代码中直接导入了 A 类,我将它们更改为使用桶并且一切正常(我仍然有警告。但它有效)

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

    ./bla,我有一个index.ts,其中包含所有模型导出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2014-04-30
      • 2016-01-29
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      相关资源
      最近更新 更多