【问题标题】:Angular8 TypeError: Cannot read property 'forEach' of undefinedAngular8 TypeError:无法读取未定义的属性“forEach”
【发布时间】:2020-03-21 12:57:24
【问题描述】:

我已经搜索了一个解决方案,但它们都不起作用。

点击按钮编辑后,它会将我重定向到编辑事件,我得到:

错误类型错误:无法读取未定义的属性“类别”

  ngOnInit() {
    this.eventService
    .getEventById(this.route.snapshot.params.id)
    .subscribe((ev) => this.event = ev);

订阅后,如果我这样做:console.log(this.event) 它返回我未定义。 而.subscribe(console.log(ev)); 给我一个对象。 不知道为什么this.event = ev 不起作用我已经在另一个组件中使用过它并且映射有效。

服务:

getEventById(id) {
    return this.httpClient.get<EventsDto>(this.urlevent + '?id=' + id);
  }

在 edit-event.component.html 中,打印了 {{event.name}} 这怎么可能 如果 this.event 像我们之前看到的那样未定义:.subscribe((ev) =&gt; this.event = ev)

【问题讨论】:

  • 在订阅中添加断点,然后在打开网络选项卡的情况下重新创建问题。您应该看到在订阅内发送的出站打包。这应该告诉您结果是您所期望的。

标签: angular typescript asynchronous undefined


【解决方案1】:

tl;dr - 通过在按钮按下函数内部调用 this.http.get() 对异步逻辑进行分组,并在其 subscribe() 方法中应用任何下游逻辑


当您处理异步代码时,您必须格外小心,以确保异步函数(例如您的 this.httpClient.get 请求)在您尝试与其交互、显示等之前已返回数据。

正如您所说的,您的 .subscribe(console.log(ev)) 正确记录了数据,但您的同步 console.log(ev) 却没有。这是因为同步的console.log(ev) 将在您的this.httpClient.get() 被调用后立即执行。由于异步数据返回需要一些时间,所以在触发同步console.log(ev) 的时间点,变量ev 仍然是undefined。从 subscribe() 块中调用 console.log(ev) 而是专门等待从 this.httpClient.get() 返回的数据,然后再执行,确保 ev 将拥有您请求的数据(或错误)。

考虑到这一点,缓解问题的一种简单方法是在按钮单击事件中调用this.http.get() 请求,并在.subscribe() 函数中包含任何下游功能。这将允许编译器保证在调用后续函数时某些数据可用。

.html

<button (click)="buttonClick()></button>

.ts

buttonClick() {
  this.eventService
    .getEventById(this.route.snapshot.params.id)
    .subscribe(ev => {
      this.event = ev
      // your code here, e.g. createEventsDto(ev)
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2021-10-29
    相关资源
    最近更新 更多