javascript - ngOnInit 和构造函数谁先运行

标签 javascript angular

当我调用构造函数中注入(inject)的服务时,我得到了未定义的信息。 该服务在 ngOnInit 方法中调用,来自 Difference between Constructor and ngOnInit我已经看到构造函数首先运行,但就我而言,我注意到相反的情况,所以我有点困惑。有没有人对此进行更多解释,谢谢。

constructor(private curveService  :ProgressCurveService, private util : UtilService) {
    this.startPickerOptions = new DatePickerOptions();
    this.endPickerOptions = new DatePickerOptions();
    //this.datePickerOptions.initialDate = new Date(Date.now());
   }

ngOnInit() {
    this.curveService.instance.getCurve(this.startDate.formatted,this.endDate.formatted,this.amplutid).
    then(res => {

        this.lineChartLabels = this.util.dateToShortString(Object.keys(res.progressPlotData))
        this.lineChartData = this.util.objectToIntArray(res.progressPlotData);
    }).catch(res => console.log('error if date selecting ...'));
}

进度曲线服务:

import { progressCurveItf } from './progress-curve/progress-curve-interface';

@Injectable()
export class ProgressCurveService {

    state : string = 'project';
  constructor(private prsCurve : PrsProgressCurveService, private projCurve : ProjProgressCurveService) { }
  get instance():progressCurveItf{

    if(this.state == 'subproject'){
        return this.prsCurve;
    } else {
        return this.projCurve;
    }
  } 

}

最佳答案

当您返回一个 progressCurveItf 类型的实例(这是一个接口(interface))时,我认为您返回的实例化有问题, 检查您是否提供 PrsProgressCurveServiceProjProgressCurveService

关于javascript - ngOnInit 和构造函数谁先运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42805460/

相关文章:

php - 使用 Php 或 Javascript 验证特定日期

javascript - 通过 JavaScript 更改 Zurb 基金会中选择框的值

javascript - HTML 选择框有关显示/隐藏 div 的 JQuery 问题

javascript - useState 我做错了什么?

angular - 如何在 Angular 中使用属性绑定(bind)与 td 属性 colspan?

Angular 2 和动态模板(远程内容)

javascript - 如何使用jquery使用输入逗号值查找日期存在与否

javascript - https ://code. angularjs.org 上的 Angular-2-Release 在哪里?

Angular 路由解析器或 onInit?

Angular 通过@Output() 向父组件传递参数