我正试图在一个组件中使用我的数据服务,但是当我点击按钮时,它给出了错误,并显示数据服务未定义。
下面是我的组件文件:
export class ProductsComponent implements OnInit {
dataSource: any;
priority: any[];
e: any;
constructor(public dataService: DataService) {
// data source stuff...
}
ngOnInit() {
console.log(this.dataService) //successfully shows DataService object
}
addToCart(e) {
console.log(e.row.data["Task_Subject"]);
console.log(this.dataService) // undefined?!?
this.dataService.addItem(e.row.data["Task_Subject"])
}
}和组件的HTML模板:
<h2 class="content-block">Products</h2>
<dx-data-grid class="dx-card wide-card" [dataSource]="dataSource" [showBorders]="false" [focusedRowEnabled]="true"
[focusedRowIndex]="0" [columnAutoWidth]="true" [columnHidingEnabled]="true">
<dxo-paging [pageSize]="10"></dxo-paging>
<dxo-pager [showPageSizeSelector]="false" [showInfo]="true"></dxo-pager>
<dxo-filter-row [visible]="true"></dxo-filter-row>
<dxi-column dataField="Task_ID" [width]="90" [hidingPriority]="2">
</dxi-column>
<dxi-column dataField="Task_Subject" [width]="190" caption="Subject" [hidingPriority]="8">
</dxi-column>
<dxi-column dataField="Task_Status" caption="Status" [hidingPriority]="6">
</dxi-column>
<dxi-column dataField="Task_Priority" caption="Priority" [hidingPriority]="5">
<dxo-lookup [dataSource]="priority" valueExpr="value" displayExpr="name">
</dxo-lookup>
</dxi-column>
<dxi-column dataField="ResponsibleEmployee.Employee_Full_Name" caption="Assigned To" [allowSorting]="false"
[hidingPriority]="7">
</dxi-column>
<dxi-column caption="Actions" type="buttons" [hidingPriority]="0">
<dxi-button icon="plus" [onClick]="addToCart">Action</dxi-button>
</dxi-column>
</dx-data-grid>当我点击'dxi- button‘上的按钮时,addToCart()函数运行。在ngOnInit函数中,显示了数据服务,但在addToCart函数中,控制台日志数据服务给了我未定义。
我做错了什么?顺便说一下,我正在使用DevExtreme。
发布于 2020-10-20 22:09:07
我认为你调用函数的方式不是在angular上下文中
尝试执行console.log(this),如果对象不是ProductsComponent类型,那么您将不再处于angular上下文中
如果是这种情况,您可以更改在html模板中调用onClick函数的方式
也许是像这样的
(onClick)="addToCart(item)"发布于 2020-10-20 22:50:35
我用一个小技巧修复了这个问题,把答案传给了其他人。Devexpress更改"this“的作用域。为了解决这个问题,我只是添加了
this.addToCart = this.addToCart.bind(this);到构造函数中,现在我可以正确使用this.dataService了!谢谢你们的帮助。
发布于 2020-10-20 23:19:54
查看devextreme组件的callback function docs,绑定是以一种非常不成角度的方式完成的。
在angular中,对于顶级组件,您可以使用()绑定。由于嵌套组件使用[]绑定语法,因此您需要向它传递一个函数,该函数绑定到您希望在函数内为“this”的对象。它建议在你的构造函数中这样做:
回调函数在组件的上下文之外执行。如果上下文很重要,则在构造函数中显式地将回调函数绑定到它。
constructor(public dataService: DataService) {
// data source stuff...
this.addToCart.bind(this);
}https://stackoverflow.com/questions/64446760
复制相似问题