首页 > 解决方案 > Angular 7 JSON.stringify“无法解析符号 JSON”

问题描述

首先,这是我第一次使用 Angular 7;我开始使用带有 ac# 后端的 Angular 7 制作应用程序,并且需要在将对象component/service发送到我的controller/service.

就像是:

export class jsonTest  {
    json: string;
    obj: myType = {} as myType;

    this.obj.someProperty = 1234;
    this.obj.anotherProperty = 'test';

    someMethod() {
        this.json = //convert obj to json
        anotherMethod(this.json);
    }
}

在寻找如何实现这一点的过程中,我遇到了两个流行的建议,一个是being JSON.stringify(),另一个是being toJson()

但是,JSON.stringify()会引发编译错误symbol JSON cannot be resolved, probably it is located in an inaccessible module.

尝试toJson(),它不被认为是任何类型的钩子。

是否有一些我缺少的进口?浏览角度文档并不能说明我的问题。

在这一点上,我正在考虑手动序列化 JSON,但如果可以的话,我真的很想避免这样做。有什么建议么?

标签: jsonangularangular7

解决方案


您的打字稿中有一些错误。尝试这样做。

export class JsonTest implements OnInit {
json: string;
obj: MyType = new MyType();

ngOnInit(): void {
    this.obj.someProperty = 1234;
    this.obj.anotherProperty = 'test';
}
someMethod() {
    this.json = JSON.stringify(this.obj);
    anotherMethod(this.json);
}}

推荐阅读