1
votes

I am trying to create my first MEAN stack to do app and am stuck. Trying to figure out how to display my data in the html but not sure how to change the response I am getting from my server so my *ngFor can display the data.

I am sure my error is somewhere in the getList() or getAllTodos() functions. I've tried adding

.map(response => response.json().todos)

to the getAllTodos() function but then I get the "res.json is not a function" error due to the updates of Http module to HttpClient module of angular 4.

I tested my route from the server using REST client and I know I am getting the correct response, which is:

{
"success": true,
"todos":
  {
"_id": "5b0dc32d1f6fa0f48ca7d374",
"item": "test",
"completed": false,
"__v": 0
},
  {
"_id": "5b0dc3b11f6fa0f48ca7d375",
"item": "1234",
"completed": false,
"__v": 0
},
  {
"_id": "5b0dc4ae1f6fa0f48ca7d376",
..........

dashboard.component.ts

export class DashboardComponent implements OnInit {
  user: Object;

  lists: List[];

  @Input() input;

  @Output() update = new EventEmitter();

  constructor(
    private authService: AuthService,
    private flashMessage: FlashMessagesService,
    private listService: ListService
  ) { }

  ngOnInit() {
    this.getLists();

    this.authService.getProfile().subscribe(profile => {
      this.user = profile.user;
    },
    err => {
      console.log(err);
      return false;
    });
  }

  getLists(): void {
    this.listService.getAllTodos()
      .subscribe(list => this.lists = list);
  }

list.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

import { List } from '../list';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class ListService {
  newTodo: any;

  constructor(private http: HttpClient) { }

  getAllTodos(): Observable<List[]> {
    return this.http.get<List[]>('http://localhost:3000/todos/lists')
  }
2

2 Answers

1
votes

Your response is an object, You need to assign todos

 this.listService.getAllTodos()
      .subscribe(list => this.lists = list.todos);
-1
votes

The response array is not a valid JSON value. todos should have been an array. The response should look something like this: { "success": true, "todos": [{ "_id": "5b0dc32d1f6fa0f48ca7d374", "item": "test", "completed": false, "__v": 0 }, { "_id": "5b0dc3b11f6fa0f48ca7d375", "item": "1234", "completed": false, "__v": 0 }]