fetch 中的 Angular 调用函数 (ngOninit)

Posted

技术标签:

【中文标题】fetch 中的 Angular 调用函数 (ngOninit)【英文标题】:Angular call function inside fetch (ngOninit) 【发布时间】:2022-01-14 06:59:31 【问题描述】:

我想在 fetch 中调用一个函数,但由于某种原因,我收到以下错误并且找不到解决方案。

 Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'myFunction')
TypeError: Cannot read properties of undefined (reading 'myFunction')

我应该如何在 fetch 中调用一个函数 -> 那么呢? 极简主义复制在下面的链接:

https://plnkr.co/edit/kizI9pLOe8XZzKYz?preview

【问题讨论】:

【参考方案1】:

当你声明一个函数时,你的上下文会丢失。

使用箭头函数来避免该错误如下:

fetch('https://www.ag-grid.com/example-assets/row-data.json').then( (response) => 
  return response.json();
).then( (data) =>
  this.myFunction(data);
)

【讨论】:

以上是关于fetch 中的 Angular 调用函数 (ngOninit)的主要内容,如果未能解决你的问题,请参考以下文章