简体   繁体   English

在Angular 4中读取JSON

[英]Reading JSON in Angular 4

I receive the following JSON data from a web service in Angular 4: 我从Angular 4中的Web服务接收以下JSON数据:

    {
        "NewDataSet": {
            "Table": [
                {
                    "DataPointID": [
                        "6520"
                    ]
               }
           ]
       }
    }

I have verified that it is valid JSON data, but when I try to return, I don't get the value. 我已经验证了它是有效的JSON数据,但是当我尝试返回时,没有得到该值。 I received it as a string and I converted it into JSON using JSON.Stringfy(obj,null,'\\t') 我以字符串形式接收它,并使用JSON.Stringfy(obj,null,'\\t')将其转换为JSON

obj.NewDataSet.Table[0].DataPointID throws obj.NewDataSet.Table[0].DataPointID引发

ERROR TypeError: Cannot read property 'Table' of undefined. 错误TypeError:无法读取未定义的属性'Table'。

I tried this on w3School in html, but it seems that it's working there. 我在w3School中以html尝试过此操作,但似乎在这里工作。 What is the issue? 有什么问题

when you get the object you should read it as 当您获得对象时,应将其读取为

this.http.get(ServiceUrls.employees.detail(this.operations.userID)).subscribe(
      detail => this.RequestSuccess(detail.json()), (error: Response) => this.RequestError(error.json())
    );

Notice there is a detail.json() so in your function you don't have to do anything else. 注意,这里有一个detail.json(),因此在您的函数中您无需执行任何其他操作。

You should create an interface and let know the get that it must return the value in the interface type. 您应该创建一个接口,并让其知道它必须返回接口类型中的值。 So your code might look something like the following: 因此,您的代码可能类似于以下内容:

export interface ThisGetInterfaceResponse {
    "NewDataSet": NewDataSetModel
}

export class NewDataSetModel {
    "Table": Table[]
}

export class Table {
   constructor(
      "DataPointID": number[]
   ) {}
}

Let's say you have httpService that is an instance of HttpClient injected in your component: 假设您在组件中注入了作为HttpClient实例的httpService:

this.httpService.get<ThisGetInterfaceResponse>(url).subscribe((res: ThisGetInterfaceResponse) => {
   console.log(res.NewDataSet.Table);
})

Also pay attention to .subscribe() because if you subscribe to the observer multiple times it will request the resource multiple times. 还请注意.subscribe()因为如果您多次订阅观察者,它将多次请求资源。 For example: 例如:

let observable = this.httpService.get<ResponseInterface>(url); observable.subscribe(); observable.subscribe(); ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM