我正在尝试创建我的第一个MEAN堆栈来执行应用程序并且卡住了。试图弄清楚如何在html中显示我的数据,但不知道如何更改我从服务器获得的响应,以便我的* ngFor可以显示数据。
我确定我的错误在getList()或getAllTodos()函数中的某处。我试过添加
.map(response => response.json().todos)
到getAllTodos()函数,但由于Http模块更新为角度为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')
}
答案 0 :(得分:1)
您的回复是一个对象,您需要指定 todos
this.listService.getAllTodos()
.subscribe(list => this.lists = list.todos);
答案 1 :(得分:-1)
响应数组不是有效的JSON值。待办事项应该是一个阵列。
响应应该如下所示:
e.type === 'click' || e.keyCode === 13