Angular连接到node.js,后者从mongodb获取数据。 效果很好,但是现在我需要将Typescript组件中的变量映射到后端node.js。
在浏览器控制台中,数据结构如下所示: Browser Console
The code within the component.ts looks like this:
ngOnInit() {
this.contactService.getContacts()
.subscribe(res => {
console.log(res);
let temp_max = res[0]['list'].map(res => res.main.temp_max)
let temp_min = res[0]['list'].map(res => res.main.temp_min)
let alldates = res[0]['list'].map(res => res.dt)
let deviceData = []
alldates.forEach((res) => {
let jsdate = new Date(res * 1000)
deviceData.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
})
console.log(deviceData)
})
}
现在我写了let temp_max = res[0]['list'].map(res => res.main.temp_max)
,但是如何用[i]代替[0],打字稿中正确的语法是什么?
我尝试了(下面的代码)并收到错误消息:
ngOnInit() {
this.contactService.getContacts()
.subscribe(res => {
console.log(res);
for (var i = 0; res.length; i++) {
let temp_max = res[i]['list'].map(res => res.main.temp_max)
let temp_min = res[i]['list'].map(res => res.main.temp_min)
let alldates = res[i]['list'].map(res => res.dt)
let deviceData = []
alldates.forEach((res) => {
let jsdate = new Date(res * 1000)
deviceData.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
})
console.log(deviceData)
})
}
}
请帮我解决:)我的问题。谢谢伊甸园
答案 0 :(得分:0)
您可以先循环res
,然后循环list
,以实现此功能,而无需任何for循环。
const temp_max = res.map((r) => r.list.map((list) => list.main.temp_max));
const temp_min= res.map((r) => r.list.map((list) => list.main.temp_min));
const alldates = res.map((r) => r.list.map((list) => list.dt));
console.log(temp_max, temp_min, alldates)
答案 1 :(得分:-2)
循环的结束条件部分缺失:
for (let i = 0; i < res.length; i++)
答案 2 :(得分:-2)
别忘了forEach也可以有一个迭代器:
res.forEach((resItem, i) => {