【问题标题】:NgFor only supports binding to Iterables such as Arrays.Cannot find differ supporting ObjectNgFor 仅支持绑定到诸如 Arrays 之类的 Iterables。找不到不同的支持对象
【发布时间】:2021-01-12 04:01:20
【问题描述】:

我在网站上遇到了很多关于同一问题的链接。但我无法解决。很抱歉再次问这种问题。

在我的项目中,我想遍历任务并显示它。我从后端获取这些任务。我可以通过控制台查看任务,但无法在网页中查看,因为它给出了错误。我尝试在 ngFor 中使用“键值”,但是当我使用时没有显示任何内容。

task.service.ts

get_tasks():Observable<Task>{
    return this.http.get<Task>('http://localhost:3000/tasks/');
  }

  createTask(task:Task){
    console.log(task);
    return this.http.post('http://localhost:3000/tasks/',task);
  }

  deleteTask(id){
    return this.http.delete('http://localhost:3000/tasks/'+id);
  }

  updateTask(task){
    return this.http.put('http://localhost:3000/tasks/'+task.id,task).pipe(map(res=>{
      console.log(res);
      }));
  }

tasks.component.ts

ngOnInit(){
    this.getTasksList();
  }

  getTasksList(){
    this.taskService.get_tasks().subscribe((task:any)=>{
      this.tasksList=task;
      console.log(this.tasksList);
    })

  }

  newTasks(event){
    event.preventDefault();
    var newList={
      _id:this.id,
      title:this.title,
      isDone:false
    }
    this.taskService.createTask(newList).subscribe((task:any)=>{
      this.tasksList.push(task);
      this.title='';
    })

  }

  removeTask(id){
    var tasks=this.tasksList;
    this.taskService.deleteTask(id).subscribe((data)=>{
      for(var i=0;i<tasks.length;i++){
        if(tasks[i]._id=id){
          tasks.splice(i,1);
        }
      }
    })

  }

task.component.html

<div class="tasks">
  <div class="tasks-list" *ngFor="let task of tasksList">
    <div class="col-md-1">
      <input type="checkbox">
    </div>
    <div class="col-md-7">
      {{task.title }}


</div>

哪里做错了?是类型吗??谁能解释我在哪里做错了。

【问题讨论】:

  • 能否分享您在控制台中看到的错误以及后端响应示例?
  • 我添加了错误@FrancescoColamonici的截图

标签: node.js angular mongodb observable ngfor


【解决方案1】:

后端似乎正在返回一个对象,该对象的数组包含在名为data 的属性中。

选项 1:您可以在控制器中分配它而不更改模板

控制器

getTasksList(){
  this.taskService.get_tasks().subscribe((task:any) => {
    this.tasksList = task['data'];
    console.log(this.tasksList);
  });
}

模板

<div class="tasks">
  <div class="tasks-list" *ngFor="let task of tasksList">
    <div class="col-md-1">
      <input type="checkbox">
    </div>
    <div class="col-md-7">
      {{ task?.title }}
    </div>
  </div>
</div>

选项2:或者不更改控制器并访问模板中的属性

getTasksList(){
  this.taskService.get_tasks().subscribe((task:any) => {
    this.tasksList = task;
    console.log(this.tasksList);
  });
}

模板

<div class="tasks">
  <div class="tasks-list" *ngFor="let task of tasksList?.data">
    <div class="col-md-1">
      <input type="checkbox">
    </div>
    <div class="col-md-7">
      {{ task?.title }}
    </div>
  </div>
</div>

选项3:或者如果可以调整后端,保持前端代码不变,调整后端返回数组[{}, {},...]而不是对象{data: [{}, {},...]}

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 2020-08-29
    • 2018-07-14
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2017-07-29
    相关资源
    最近更新 更多