angular - 如何修复 "Cannot set property of undefined"?

标签 angular typescript rxjs angular9

我正在以 angular 制作倒数计时器,但在尝试从另一个组件调用变量时遇到 TypeError。我无法弄清楚究竟是什么导致了这个问题。这是我关注的视频:Countdown Timer下面是我的代码:

Timer.component.ts

import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-timer',
  template: `<span>{{ currentValue }}</span>`,
  styleUrls: ['./timer.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TimerComponent implements OnInit {

  @Input() startAt = 0;

  @Output() counter = new EventEmitter<string>();

  currentValue = '';
  constructor(private changeDetector: ChangeDetectorRef) { }

  ngOnInit(){
  }

  public start(){
    this.currentValue = this.formatValue(this.startAt);
    this.changeDetector .detectChanges();
  }

  private formatValue(v){
    const minutes = Math.floor(v/60);
    const formattedMinutes = (minutes > 9) ? minutes : ('0' + minutes);

    const seconds = v%60;
    const formattedSeconds = (seconds > 9) ? seconds : ('0' + seconds);

    return `${ formattedMinutes } : ${ formattedSeconds }`;
  }
}

question.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { TimerComponent } from '../timer/timer.component';

export class QuestionComponent implements OnInit {

  @ViewChild('counter', { read: TimerComponent })
  private counter: TimerComponent;

  ngOnInit() {
      this.counter.startAt = 2700;
      this.counter.start();
  }
}

question.component.html
<app-timer #counter></app-timer>

错误
core.js:6185 ERROR TypeError: Cannot set property 'startAt' of undefined
    at QuestionComponent.ngOnInit (question.component.ts:122)
    at callHook (core.js:4686)
    at callHooks (core.js:4650)
    at executeInitAndCheckHooks (core.js:4591)
    at refreshView (core.js:11814)
    at refreshDynamicEmbeddedViews (core.js:13154)
    at refreshView (core.js:11819)
    at refreshComponent (core.js:13229)
    at refreshChildComponents (core.js:11527)
    at refreshView (core.js:11848)

这是我的代码。请帮帮我。

最佳答案

您需要使用 AfterViewInit 等待子进程的初始化。钩。

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';

export class QuestionComponent implements OnInit, AfterViewInit {

    ngAfterViewInit() {
        this.counter.startAt = 2700;
        this.counter.start();
    }

}

关于angular - 如何修复 "Cannot set property of undefined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61084259/

相关文章:

typescript - 为 react 导航 Prop 添加强类型

javascript - Ionic 2 - 属性不存在类型错误

angular - RxJS:WebSocket 重连处理

Angular2 RC1 karma 错误 - 无法找到@angular/core/testing

angular - 如何使用 TypeScript 返回正确的 Promise

google-maps - 在子组件中使用 SebM 谷歌地图模块显示空白 map

css - Angular Material 默认样式/动画在自定义主题后不起作用

android - 使用模块解析器时的 Metro bundler 错误

javascript - RxJS 在 JS 生态系统和演变中的地位是什么?

javascript - 如何测试 RxJS 事件