Angular 在使用Observable时,有没有办法将复杂的json数据映射到typescript中的接口上?
我正在尝试制作简单的web新闻阅读器,主要基于google新闻api()。我做了所有事情,比如AlwaysSO服务、模型等,但我在将数据映射到具体接口上时遇到了问题。Google api以以下格式返回其中一个端点(“头条新闻”)数据:Angular 在使用Observable时,有没有办法将复杂的json数据映射到typescript中的接口上?,angular,typescript,rest,google-news,Angular,Typescript,Rest,Google News,我正在尝试制作简单的web新闻阅读器,主要基于google新闻api()。我做了所有事情,比如AlwaysSO服务、模型等,但我在将数据映射到具体接口上时遇到了问题。Google api以以下格式返回其中一个端点(“头条新闻”)数据: { "status": "ok", "totalResults": 38, "articles": [ { "source": { "id": "the-new-york-times",
{
"status": "ok",
"totalResults": 38,
"articles": [
{
"source": {
"id": "the-new-york-times",
"name": "The New York Times"
},
"author": null,
"title": "Hong Kong Protesters Clash with Police Amid Fears of Mob
Violence - The New York Times",
"description": "some description",
"url": "https://www.nytimes.com/2019/08/11/world/asia/hong-kong-
protest.html",
"urlToImage":
"https://static01.nyt.com/images/2019/08/11/world/11hongkong15/
11hongkong15-facebookJumbo.jpg",
"publishedAt": "2019-08-11T11:19:03Z",
"content": "some content… [+751 chars]"
},
(...and many many more articles)
]
}
我只需要物品。我知道,如果我像这样从api获取这些数据,我可以调用myvariablename.articles,但这对我来说并不正确
我的第一个尝试是使用rxjs映射方法进行映射。但我在控制台中得到一个错误,即在项目模型中并没有属性项目。所以我准备了响应模型和嵌套文章作为响应模型(接口)中的属性。我也犯了同样的错误。我一直在想,也许在方法Observable中定义有一些问题,所以我切换到Response,但运气不好,现在我订阅的组件和使用的服务方法也出现了错误,它说:“Type Response[]不可分配给Type Article[]”
顶级新闻服务
回应
top-news-component.ts
我希望能够在服务中映射数据并仅返回项目,然后(如果可能的话)在我的组件中获取该数据并将其分配给已定义类型为Article[]的已创建变量。您正在使用的
this.httpClient.get<Response[]>
由于您(尝试)将此响应映射到一系列文章,那么您的服务返回的可观察内容是可观察内容
,而不是可观察内容
。应该如此
this.httpClient.get<Response>
public getAll(): Observable<Article[]> {
export interface Response {
status: string;
totalResults: number;
articles: Article[];
}
这也是错误的。响应不包含一篇文章。它包含一个项目数组。看看JSON:
{
"status": "ok", // one status string
"totalResults": 38, // one totalResults number
"articles": [ // an **array** of articles
..
]
}
应该如此
this.httpClient.get<Response>
public getAll(): Observable<Article[]> {
export interface Response {
status: string;
totalResults: number;
articles: Article[];
}
该死的,我盯着代码看了两个小时,我被什么问题弄糊涂了。你是100%对的,我得到的是一个响应,期望得到很多响应,接口实现是错误的,因为我期望有一篇文章。但有一件事对我来说很奇怪,那就是可观察的,因为我一直认为我应该像从其他地方得到的整个物体一样使用它(阅读回应)不是我感兴趣的部分,也不是我想从函数返回的部分。无论如何,我都会将此标记为我问题的正确答案,并感谢您的帮助。httpClient.get(…)是可观察的。但是map()操作符的全部要点是创建另一个可观察对象,发出不同的东西(一个映射或转换为其他东西的响应)。所以map()操作符从一个可观察对象创建一个可观察对象。因为对我来说,这是一个很有魅力的角色,但听起来也有点奇怪。但这一解释很有道理,而且非常清楚。再次感谢你的帮助
{
"status": "ok", // one status string
"totalResults": 38, // one totalResults number
"articles": [ // an **array** of articles
..
]
}
export interface Response {
status: string;
totalResults: number;
articles: Article[];
}