网站搜索

javascript - 当将函数从父组件传递到子组件的 Input() 属性时丢失上下文


我正在将一个 function 从我的父组件传递到我的子组件的 Input() 属性。

问题是,父组件的函数在子组件中被调用,而 this 关键字现在指的是子组件的上下文,而不是父组件的上下文。

这是我在父组件中所做的一个示例:

export class CustomerComponent implements OnInit {
    next(continuationToken: string): Observable<CustomerSearchResult> {
        console.log('invoked');
        return this.customerService.searchCustomersPaged("andrew");
    }
}

在我的父组件的模板中(我通过名为 'nextDelegate' 的输入参数传递 'next' 函数):

<app-datatable [hidden]="!customersByFirstNameHasResults" [nextDelegate]="next" [serverSidePaging]="true" id="customersByFirstName" [showDeleteButton]="false" [showEditButton]="true" [responseModelObservable]="customersByFirstName"
      modelTypeName="customer" (editRow)="editCustomer($event)">
    </app-datatable>

最后,在我的子组件中,我尝试调用传入的方法,但context不正确。

export class DatatableComponent implements AfterViewInit, OnDestroy, OnInit {
  @Input() nextDelegate: (continuationToken: string) => Observable<CustomerSearchResult>;

private initializeDtOptions() {
// storing current class reference in a variable to use it in jQuery 

// function because we can't 
    //use arrow function as we might need both this' in the function
    if (this.serverSidePaging) {
      this.dtOptions = {
        pagingType: 'simple',
        serverSide: true,
        processing: true,
        pageLength: 10,
        deferLoading: 100, //this.totalRecords
        ajax: (p, callback) => {
          //called here
          that.nextDelegate("").subscribe(x => {
            callback({

            })
          });

        }
      };
    } else {
      this.dtOptions = {
        pagingType: 'full_numbers',
        columns: this.columnSettings
      };
    }
  }
}

答案#1

根据上下文,我认为你的意思是作用域。这是错误的,因为你的函数定义方式不对。

尝试使用:

export class CustomerComponent implements OnInit {
    public next = (continuationToken: string): Observable<CustomerSearchResult> => {
        console.log('invoked');
        return this.customerService.searchCustomersPaged("andrew");
    }
}

话虽如此,这确实看起来有点问题。我建议使用输出,或者注入一个服务来处理这个问题。