J1297
J1297

Reputation: 61

retrieve array data from api to angular app

I'm trying to get an array of data from a local api and display it in my Angular6 App. Getting the content from the api works, but I can't manage to parse the data and output it where i want to. I'm searching Google pages up and down for days for that Problem, but somehow no solution seems to work for me (or i'm actually too stupid to implement it the right way :D) Hopefully you guys can help me.

API: (( Content = require('./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}) })

Content Model Schema:

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

Service:

  getContent(): Observable<mycontent[]> {
    return this.http.get<mycontent[]>('/api/retrieveContent')
      .pipe(tap(data => JSON.stringify(data as mycontent[])))
  }

content.ts file (containing my mycontent Model):

export interface mycontent {
    status: boolean,
    subject: string,
    customer: string,
    task: string,
    date: string,
    id: string
}

Component (in ngOnInit()) (Im initializing contents as an array earlier in that component) :

  this.contentServ.getContent()
      .subscribe(data => this.contents = data)

And finally im trying to output in my component.html file:

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

Upvotes: 3

Views: 826

Answers (2)

J1297
J1297

Reputation: 61

Wow, that was really fast. Exactly what I needed, thank you so much @mast3rd3mon

res.status(200).json('data': contents)

Didn't work just like that, but if i just parse contents in there, its working perfectly fine.

You were also right when you said i could remove the pipe.

Again, thank you so much for that, i was short before going crazy on this one.

Lots of greetings, J1297

Upvotes: 0

mast3rd3mon
mast3rd3mon

Reputation: 8835

const content = await Content.find({}) wont work. the data is returned in the method, not by it. Try the following:

Content.find({}, function(err, contents) {
    if (err) {
        res.status(500).json('Error')
    } else {
        res.status(200).json('data': contents)
    }
})

You might also be able to remove the pipe. If you cant, try changing the pipe to:

.pipe(map(res => res.json().data))

Upvotes: 1

Related Questions