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

问题描述 投票:1回答:1

概观

我正在学习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组件:

这是我通过id调用track的html的一部分

<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函数更好的方法。
angular typescript
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.