错误:找不到不同的支持对象'[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",
..........

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

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

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

响应数组不是有效的 JSON 值。 待办事项应该是一个数组。 响应应如下所示: { "success": true, "todos": [{ "_id": "5b0dc32d1f6fa0f48ca7d374", "item": "test", "completed": false, "__v": 0 }, { "_id": "5b0dc3b11f6fa0f48ca7d375", "item": "1234", "completed": false, "__v": 0 }]

相关内容

  • 没有找到相关文章

最新更新