【问题标题】:Angular Type Script undefined error with parent variable带有父变量的Angular Typescript未定义错误
【发布时间】:2020-03-31 16:52:00
【问题描述】:

有人知道我为什么会收到未定义的错误吗?

export abstract class BaseEditorComponent implements IPropertyEditor, OnDestroy {

  @Input()
  public element: BpmnJS.IRegistryElement; 

--more code here


export class CommonPropertiesEditorComponent extends BaseEditorComponent {

  constructor(
  ) {
    super();
  }

  public get elementId(): string {
    return this.element.id;
  } 

export class ExclusiveGatewayEditorComponent extends CommonPropertiesEditorComponent implements OnInit {

  public model: IUserTaskDef;
  public outGoing: Sequences[];

  constructor(
    private service: ExclusiveGatewayService
  ) {
    super();
    this.model = {} as any;
    this.outGoing = this.getOutGoingSequences();
  }

  public getOutGoingSequences(): Sequences[] {

    return this.service.getOutgoingSequences(this.elementId); //This is undefined.
  }

TypeError:无法读取未定义的属性“id” 在 ExclusiveGatewayEditorComponent.get [as elementId] (common-properties-editor.component.ts:16) 在 ExclusiveGatewayEditorComponent.push../src/app/properties/editors/gateways/exclusive-gateway/exclusive-gateway-editor.component.ts.ExclusiveGatewayEditorComponent.getOutGoingSequences (exclusive-gateway-editor.component.ts:27) 在新的 ExclusiveGatewayEditorComponent (exclusive-gateway-editor.component.ts:22) 在 createClass (core.js:21148) 在 createDirectiveInstance (core.js:21027) 在 createViewNodes (core.js:29387) 在 createRootView (core.js:29301) 在 callWithDebugContext (core.js:30309) 在 Object.debugCreateRootView [as createRootView] (core.js:29819) 在 ComponentFactory_.push../node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create (core.js:20506)

如果我在 html 页面中输入相同的函数,它可以正常工作并显示 element.id 的值

<input class="form-control" type="text" name="txtId" [(ngModel)]="elementId" readonly>

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您不应该尝试从构造函数访问@Input() 属性,此时它们不存在。你应该改用ngOnInit() 方法。

    export class ExclusiveGatewayEditorComponent extends CommonPropertiesEditorComponent implements OnInit {
    
      // ...
    
      constructor(
        private service: ExclusiveGatewayService
      ) {
        super();
        this.model = {} as any;    
      }
    
      ngOnInit() {
        this.outGoing = this.getOutGoingSequences();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多