首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角2+使用Alertifyjs错误TypeError:无法读取属性

角2+使用Alertifyjs错误TypeError:无法读取属性
EN

Stack Overflow用户
提问于 2018-08-21 11:09:54
回答 2查看 258关注 0票数 0
代码语言:javascript
复制
declare var alertify:any;
export class ExamplComponent implements OnInit {
    itemList = []

    deleteItem(idx) {
    alertify.confirm('Are you sure delete this record.', function() {
      this.itemList.slice(idx,1);
    })
  }
}

html页面

代码语言:javascript
复制
< div *ngFor="let item of itemList;let indx = index" style="text-align: center">
    <button class="text-btn text-danger" (click)="deleteItem(indx)" ><i class="fa fa-trash"></i></button>
</div>

来源库:https://alertifyjs.com/confirm.html 错误消息

代码语言:javascript
复制
ERROR TypeError: Cannot read property 'itemList' of undefined
EN

回答 2

Stack Overflow用户

发布于 2018-08-21 11:12:26

使用fat arrow =>而不是function

代码语言:javascript
复制
deleteItem(idx) {
    alertify.confirm('Are you sure delete this record.', ()=> {
      this.itemList.slice(idx,1);
    })
}
票数 1
EN

Stack Overflow用户

发布于 2018-08-21 11:13:41

问题在于作为参数传递给alertify.confirm()的函数。在本例中,当您使用function()声明一个函数时,它有它自己的this;因此,当您编写this.itemList代码时,您将指向undefined,因为它并不存在于您的函数中。

尝试使用箭头函数(() => {}),它们从当前作用域继承this,因此在回调中使用是安全的。

代码语言:javascript
复制
deleteItem(idx) {
    alertify.confirm('Are you sure delete this record.', () => {
      this.itemList.slice(idx, 1)
    })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51947379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档