简体   繁体   English

来自响应主体的angular5 JSON

[英]angular5 JSON from response body

I got some trouble to add my data from get response into my data array. 将获取响应中的数据添加到数据数组时遇到了一些麻烦。 I just read that you do not have to call .json now ( it not even compile ) because json is now part of angular httpClient. 我刚刚读到您现在不必调用.json(它甚至不编译),因为json现在是有角度的httpClient的一部分。

But then, how do you put the date of the request into an array to be use with *ngFor... or is there another easier way of looping data into html... 但是,然后,您如何将请求的日期放入要与* ngFor ...一起使用的数组中,或者还有另一种更简单的将数据循环到html中的方法...

I got my service: 我得到了我的服务:

return this.http.get(this.url).do((res : Response) => res);

then in my module: 然后在我的模块中:

dataArray = [];
///***///
this.getdata.getData().subscribe(data => this.dataArray = data);

how do I convert the type response: data to the array type ? 如何将类型响应:数据转换为数组类型?

[EDIT]: Ok, I made some progress. [编辑]:好的,我取得了一些进展。 Following @Azzi advice, I have to cast my data. 按照@Azzi的建议,我必须转换数据。 And I found this tutorial that do want I want to do: 我发现本教程确实想要做:

angular example - http 角度示例-http

In that I also found that I should make an interface that reflect my data model. 在那我还发现我应该创建一个反映我的数据模型的接口。 That in made in : pages/home/channel.ts 内建于:pages / home / channel.ts

I been able to compile request and get method but my array still keep undefine. 我已经能够编译请求并获取方法,但是我的数组仍然未定义。

here the git of the project: arduino-thermostat 这是项目的git: arduino-thermostat

If you know you will be getting an array, you can cast it like this 如果您知道将要得到一个数组,则可以像这样强制转换

dataArray = [];
///***///
this.getdata.getData().subscribe(data => this.dataArray = <any[]> data);

here, data would be of type any which you probably want to cast using the <> to an array of any type 在这里,数据是类型的any您可能需要使用投<>于任何类型的数组

Update your service to map the result returned into an Array: 更新您的服务以将返回的结果映射到Array中:

return this.http.get<Array<any>>(this.url);

Declare an array in your module to store your data and instantiate it: 在模块中声明一个数组以存储数据并实例化它:

dataArray: Array<any> = [];

Then subscribe to the service in your module, the mapping will be done for you: 然后在您的模块中订阅服务,映射将为您完成:

this.getData().subscribe(data => {
                this.dataArray = data;
            })

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

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