代码之家  ›  专栏  ›  技术社区  ›  monstertjie_za

从父组件向子组件的Input()属性传递函数时丢失上下文

  •  0
  • monstertjie_za  · 技术社区  · 7 年前

    我经过一个 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 回复  |  直到 7 年前
        1
  •  1
  •   Glitcher    7 年前

    尝试使用:

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