将对象转换为数组时,Angular中的Http GET方法出现错误



我正试图从firebase中获取一个包含以下详细信息的简单post数据。在使用rxjs映射运算符将javascript对象转换为数组的部分,我遇到了错误。我期望的输出是一个包含三个键值对的数组。

我在作为javascript对象的responseData中得到了正确的响应,但转换为数组的部分产生了错误。

存储在火库中的数据:

posts
-MgsgDidteNiYoG4auXX
content: "Test content"
title: "Test"

下面是我写的方法:

private fetchPosts() {
this.http.get('https://***/posts.json')
.pipe(map(responseData => {
let postsArray = [];
for (let key in responseData) {
if (responseData.hasOwnProperty(key)) {
postsArray.push({ ...responseData[key],  id: key})
}
}
return postsArray;
}))
.subscribe(posts => {
console.log(posts);
});
}

我期望如下:

id: -MgsgDidteNiYoG4auXX
content: "Test content"
title: "Test"

得到的错误如下:

Error: src/app/app.component.ts:51:32 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'.
No index signature with a parameter of type 'string' was found on type 'Object'.
51           postsArray.push({ ...responseData[key],  id: key})

提前感谢。。。

从我的评论中扩展,添加类型定义将消除当前问题。

pipe(map((responseData: any) => {

理想情况下,这将是一种特定的类型,而不是any


其次,我相信您希望做的是将作为子对象值的父键与它自己的键id合并。为此,您可以使用Object.entries()功能

尝试以下

工作片段:

const responseData = {
"-MgsgDidteNiYoG4auXX": {
content: "Test content",
title: "Test"
}
}
let result;
for (const [key, value] of Object.entries(responseData)) {
result = { ...value, id: key };
}
console.log(result);

this.http.get('https://***/posts.json').pipe(
map((responseData: any) => {
let result: any;
for (const [key, value] of Object.entries(responseData)) {
const result = { ...value, id: key };
}
return result;
})
)

最新更新