【问题标题】:How to see fields in data (subscribe) in Angular如何在 Angular 中查看数据中的字段(订阅)
【发布时间】:2021-10-06 20:03:37
【问题描述】:

我想根据IdEmployee选择我想放入tasks数组的Objects 我试图显示数据的内容(其中有“IdEmployee”字段),但是当我显示它时,我可以看到:data.IdEmployee = undefined

在 html 文件中,我可以从我的数据库中看到整个数组

@Component({
  selector: 'app-display-tasks',
  templateUrl: './display-tasks.component.html',
  styleUrls: ['./display-tasks.component.css']
})
export class DisplayTasksComponent implements OnInit {

  constructor(private http:HttpClient) { }
  tasks:any=[]

  ngOnInit(): void {
    this.refreshList();
  }

  refreshList(){
    this.http.get<any>(environment.API_URL+'task')
    .subscribe(data=>{
      this.tasks=data;
      alert("data.IdEmployee = "+data.IdEmployee)
    })
  }
}

【问题讨论】:

  • 能否分享一下console.log(data)的结果;请?您可能以错误的方式遍历 JSON(或响应)。
  • “数据”的类型是什么? “数据”可能没有名为 idEmployee 的属性。
  • 数据的类型是object,所以如果我显示console.log(data),我可以看到[Object object]
  • 请做console.log(JSON.stringify(data))以便打印对象的内容
  • 现在我看到了数据库的内容:[{"Id":1,"IdEmployee":11111111,"TaskText":"Prepare task1","AssignDate":"2021-07-07T00 :00:00","DueDate":"2021-08-08T00:00:00"}]

标签: angular subscribe ngoninit


【解决方案1】:

您正在返回一个对象数组作为数据。

试试:

alert("data.IdEmployee = " + tasks[0].IdEmployee)

这样,您将获取数组中第一个对象的 IdEmployee。

如果您总是只返回一个对象,您可能需要考虑将后端更改为只返回一个对象而不是一组对象。

(我怀疑你想遍历一个数组并提醒所有 IdEmployee 的?)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2020-11-25
    • 2012-12-28
    • 2015-12-04
    • 2019-11-25
    相关资源
    最近更新 更多