首页 > 解决方案 > 将数组数据从 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>

标签: javascripthtmltypescriptangular6

解决方案


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))

推荐阅读