0

我正在尝试在组件中使用我的数据服务,但是当我单击按钮时它会给出错误并说数据服务未定义。

这是我的组件文件:

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。

4

3 回答 3

1

我认为您调用函数的方式不在角度上下文中

尝试做一个console.log(this),如果对象不是 ProductsComponent 类型,那么你不再处于角度上下文中

如果是这种情况,您可以更改在 html 模板中调用 onClick 函数的方式

也许像

(onClick)="addToCart(item)"
于 2020-10-20T14:09:06.910 回答
0

Looking at the callback function docs for devextreme components, the binding is done in a very un-angular way.

In angular and for top-level components you can use the () binding. Since nested components use the [] binding syntax, you need to pass it a function that is bound to the object you wish to be 'this' inside the function. It recommends doing that in your constructor:

Callback functions are executed outside the component's context. If the context is important, explicitly bind the callback function to it in the constructor.

  constructor(public dataService: DataService) {
      // data source stuff...
      this.addToCart.bind(this);
  }
于 2020-10-20T15:19:54.233 回答
0

我修复了一个小技巧,将答案发布给其他人。Devexpress 更改了“this”的范围。为了解决这个问题,我刚刚添加了

this.addToCart = this.addToCart.bind(this);

进入构造函数,现在我可以正确使用 this.dataService 了!谢谢你们的帮助。

于 2020-10-20T14:50:35.473 回答