Angular8 TypeError: Cannot read property 'forEach' of undefined
Angular8 TypeError: Cannot read property 'forEach' of undefined
我已经搜索了一个解决方案,但 none 个有效。
点击按钮编辑后,它会将我重定向到编辑事件,我得到:
ERROR TypeError: Cannot read property 'categories' of undefined
ngOnInit() {
this.eventService
.getEventById(this.route.snapshot.params.id)
.subscribe((ev) => this.event = ev);
订阅后,如果我这样做:console.log(this.event) returns 我未定义。
而 .subscribe(console.log(ev));
returns 我是一个对象。
不知道为什么 this.event = ev
不起作用我已经在另一个组件中使用了它并且映射有效。
服务:
getEventById(id) {
return this.httpClient.get<EventsDto>(this.urlevent + '?id=' + id);
}
在 edit-event.component.html 中,打印了 {{event.name}} 这怎么可能
如果 this.event 未定义,正如我们之前看到的那样:.subscribe((ev) => this.event = ev)
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)
});
我已经搜索了一个解决方案,但 none 个有效。
点击按钮编辑后,它会将我重定向到编辑事件,我得到:
ERROR TypeError: Cannot read property 'categories' of undefined
ngOnInit() {
this.eventService
.getEventById(this.route.snapshot.params.id)
.subscribe((ev) => this.event = ev);
订阅后,如果我这样做:console.log(this.event) returns 我未定义。
而 .subscribe(console.log(ev));
returns 我是一个对象。
不知道为什么 this.event = ev
不起作用我已经在另一个组件中使用了它并且映射有效。
服务:
getEventById(id) {
return this.httpClient.get<EventsDto>(this.urlevent + '?id=' + id);
}
在 edit-event.component.html 中,打印了 {{event.name}} 这怎么可能
如果 this.event 未定义,正如我们之前看到的那样:.subscribe((ev) => this.event = ev)
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)
});