函数内部的函数不是函数,并且未定义

时间:2019-02-28 23:20:20

标签: angular typescript

概述

我正在学习Angular和JHipster,并且试图获取集合中对象的ID。

我正在尝试使用trackBy获取ID,但出现此错误:

[Error] ERROR – TypeError: this.cargarElementosFoda is not a function. (In 'this.cargarElementosFoda(item.id)', 'this.cargarElementosFoda' is undefined)

    TypeError: this.cargarElementosFoda is not a function. (In 'this.cargarElementosFoda(item.id)', 'this.cargarElementosFoda' is undefined)trackIdcheckdiffngDoCheckcheckAndUpdateDirectiveInlinedebugCheckAndUpdateNodedebugCheckDirectivesFn(función anónima)checkAndUpdateViewcallViewActionexecEmbeddedViewsActioncheckAndUpdateViewcallViewActionexecComponentViewsActioncheckAndUpdateViewcallViewActionexecEmbeddedViewsActioncheckAndUpdateViewcallViewActionexecComponentViewsActioncheckAndUpdateViewcallWithDebugContextdetectChangesforEachtick(función anónima)onInvokerunnext(función anónima)__tryOrUnsubnext_nextnextnextemitcheckStableonLeaveonInvokeTaskrunTaskinvokeTaskinvokeTaskglobalZoneAwareCallback
        error
        View_PlanEstrategicoDetailComponent_1 (PlanEstrategicoDetailComponent.ngfactory.js:337)
        logError (core.js:12446)
        (función anónima)
        handleError (core.js:1922)
        run (zone.js:137)
        tick (core.js:5374)
        (función anónima) (core.js:5210:110)
        onInvoke (core.js:4343)
        run (zone.js:137)
        next (core.js:5210:85)
        (función anónima) (core.js:3993)
        __tryOrUnsub (Subscriber.js:262)
        next (Subscriber.js:200)
        _next (Subscriber.js:138)
        next (Subscriber.js:102)
        next (Subject.js:64)
        emit (core.js:3985)
        checkStable (core.js:4312)
        onLeave (core.js:4379)
        onInvokeTask (core.js:4337)
        runTask (zone.js:187)
        invokeTask (zone.js:495)
        invokeTask (zone.js:1539)
        globalZoneAwareCallback (zone.js:1576)

我不知道为什么会这样,因为我所有其他功能都运行良好。

这是TS组件:

      import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http';
import { JhiEventManager, JhiParseLinks, JhiAlertService } from 'ng-jhipster';

import { DiagnosticoFodaService } from 'app/entities/diagnostico-foda';
import { IPlanEstrategico } from 'app/shared/model/plan-estrategico.model';
import { IDiagnosticoFoda } from 'app/shared/model/diagnostico-foda.model';
import {IElementosDiagnosticoFoda} from 'app/shared/model/elementos-diagnostico-foda.model';
import { ElementosDiagnosticoFodaService } from 'app/entities/elementos-diagnostico-foda';
@Component({
    selector: 'sigem-plan-estrategico-detail',
    templateUrl: './plan-estrategico-detail.component.html'
})
export class PlanEstrategicoDetailComponent implements OnInit {
    planEstrategico: IPlanEstrategico; 
    diagnosticoFodas: IDiagnosticoFoda[];
    elementosDiagnosticoFodas : IElementosDiagnosticoFoda[];
    elementosFodas: IDiagnosticoFoda[];
    idPlan : number;

    constructor(
        private jhiAlertService: JhiAlertService, 
        private activatedRoute: ActivatedRoute,
        private diagnosticoFodaService: DiagnosticoFodaService,
        private elementosDiagnosticoFodaService : ElementosDiagnosticoFodaService) {}

    ngOnInit() {
        this.activatedRoute.data.subscribe(({ planEstrategico }) => {
            this.planEstrategico = planEstrategico;
            this.idPlan = planEstrategico.id; 
            this.cargarAnaliziFoda(this.idPlan);
        });

    }

    previousState() {
        window.history.back();
    }
    private onError(errorMessage: string) {
        this.jhiAlertService.error(errorMessage, null, null);
    }

    cargarAnaliziFoda(id){
        this.diagnosticoFodaService.findByPlan(id).subscribe(
            (res: HttpResponse<IDiagnosticoFoda[]>) => {
                this.diagnosticoFodas = res.body;   
            },
            (res: HttpErrorResponse) => this.onError(res.message)
        );
    }
    cargarElementosFoda(id_foda){ 
        /*this.elementosDiagnosticoFodaService.findByFODA(id_foda).subscribe(
            (res: HttpResponse<IElementosDiagnosticoFoda[]>) => {
                this.elementosDiagnosticoFodas = res.body;   
                console.log(this.elementosDiagnosticoFodas);
            },
            (res: HttpErrorResponse) => this.onError(res.message)
        );*/
    }
    trackId(index: number, item: IDiagnosticoFoda) {
        console.log('el id de este diagnostico foda es' + item.id);
        this.cargarElementosFoda(item.id); 
    }


}

和HTML组件:

这是html的一部分,我通过id调用跟踪

<ngb-panel  *ngFor="let diagnosticoFoda of diagnosticoFodas;trackBy: trackId">
<ng-template  ngbPanelTitle>
<span > Diagnostico FODA {{diagnosticoFoda.nombre}} 
</span>
</ng-template>

注释

  • 我真的对Angular,TypeScript和Jhipster陌生。
  • 如果我错过了重要的事情,请在评论中让我知道,我将添加到问题中。
  • 我只是想获得diagnosticoFoda.id,所以也许更好 trackBy功能的方式。

1 个答案:

答案 0 :(得分:1)

问题

我的猜测是事件处理程序正在调用trackId方法。如果我们从事件处理程序中调用方法,则该方法不再将其this绑定到该类的实例。由于this不再绑定到该类的实例,因此cargarElementosFoda方法是未定义的,这就是您的错误状态。

一个解决方案

trackId(而不是方法)放入an arrow function。这样可以确保this绑定到该类的实例,即使从事件中调用了箭头函数。

trackId = (index: number, item: IDiagnosticoFoda) => {
    console.log('el id de este diagnostico foda es' + item.id);
    this.cargarElementosFoda(item.id); 
}

更多详细信息

这是一个简化的示例,其中一个事件调用箭头函数,另一个事件调用方法。请注意,仅当从该类的实例调用该方法时,该方法才将this绑定到该类。

class Foo {

  someMethod() {
    console.log('someMethod:' + (this instanceof Foo));
  }

  someArrowFunction = () => {
    console.log('someArrowFunction:' + (this instanceof Foo));
  };
}

const foo = new Foo();

// when called from an instance of the class,
// both the arrow function and the method are bound to an instance of Foo
foo.someArrowFunction();
foo.someMethod();

// when not called from an event
// the arrow function remains bound to the instance of Foo
document
  .getElementById('btn1')
  .addEventListener("click", foo.someArrowFunction);

// when not called from an event
// the  method is no longer bound the instance of Foo
document
  .getElementById('btn2')
  .addEventListener("click", foo.someMethod);
<button id="btn1">Invoke Arrow Function</button>
<button id="btn2">Invoke Method</button>