javascript - 将数组数据从 api 检索到 Angular 应用程序
问题描述
我正在尝试从本地 api 获取一组数据并将其显示在我的 Angular6 应用程序中。从 api 获取内容有效,但我无法解析数据并将其输出到我想要的位置。我在谷歌页面上下搜索了几天来解决这个问题,但不知何故似乎没有解决方案对我有用(或者我实际上太愚蠢了,无法以正确的方式实现它:D)希望你们能帮助我。
API:((内容=需要('./models/content')
app.get('/api/retrieveContent', async (req, res) => {
const content = await Content.find({})
//console.log(content)
if(!content) {
res.json({
status: false,
message: 'Content does not exist'
})
return
}
res.json({content}) })
内容模型架构:
const mongoose = require('mongoose')
const ContentSchema = new mongoose.Schema({
subject: String,
customer: String,
task: String,
date: Date
})
const Content = mongoose.model('Content', ContentSchema)
module.exports = Content
服务:
getContent(): Observable<mycontent[]> {
return this.http.get<mycontent[]>('/api/retrieveContent')
.pipe(tap(data => JSON.stringify(data as mycontent[])))
}
content.ts 文件(包含我的 mycontent 模型):
export interface mycontent {
status: boolean,
subject: string,
customer: string,
task: string,
date: string,
id: string
}
组件(在 ngOnInit() 中)(我在该组件的前面将内容初始化为数组):
this.contentServ.getContent()
.subscribe(data => this.contents = data)
最后我试图在我的 component.html 文件中输出:
<ul *ngFor="let content of contents">
<li> {{content.subject}} </li>
<li> {{content.customer}} </li>
<li> {{content.task}} </li>
<li> {{content.date}} </li>
<li> {{content.id}} </li>
</ul>
解决方案
const content = await Content.find({})
不会工作。数据在方法中返回,而不是由它返回。尝试以下操作:
Content.find({}, function(err, contents) {
if (err) {
res.status(500).json('Error')
} else {
res.status(200).json('data': contents)
}
})
您也许还可以移除管道。如果不能,请尝试将管道更改为:
.pipe(map(res => res.json().data))
推荐阅读
- java - 是否可以创建一个“超级”变量,然后将其更改为子类类型并能够访问子类方法
- class - Kotlin 继承/子类
- git - 手动比较功能分支的主要类并仅进行这些更改,或者我应该将主要开发分支合并到此功能中
- html - Blazor HTML 渲染问题
- python - 网页抓取指定表
- c++ - 将 -lcrypto 与未定义的引用链接的 Mingw32 错误
- reactjs - React 保持旧状态 - 新状态未更新
- kubernetes - 如果未指定主机,如何访问 k8s 入口
- ruby-on-rails - Rails路由重定向使用约束和块?
- scala - Scala Spark,比较两个 DataFrames 并选择另一列的值