首页 > 解决方案 > 错误:找不到不同的支持对象“[object Object]”

问题描述

我正在尝试创建我的第一个 MEAN 堆栈来执行应用程序并且被卡住了。试图弄清楚如何在 html 中显示我的数据,但不确定如何更改我从服务器获得的响应,以便我的 *ngFor 可以显示数据。

我确定我的错误出现在 getList() 或 getAllTodos() 函数中。我试过添加

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

到 getAllTodos() 函数,但由于 Http 模块更新为 Angular 4 的 HttpClient 模块,我得到“res.json 不是函数”错误。

我使用 REST 客户端测试了来自服务器的路由,我知道我得到了正确的响应,即:

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

仪表板.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);
  }

列表.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')
  }

标签: angularmean-stack

解决方案


您的响应是一个对象,您需要分配todos

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

推荐阅读