Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何调用ngOnInit中的事件方法_Angular - Fatal编程技术网

Angular 如何调用ngOnInit中的事件方法

Angular 如何调用ngOnInit中的事件方法,angular,Angular,我试图调用ngOnInit中的事件方法 export class AppComponent { currentMinute;addedMinute;mousemove constructor(private datePipe: DatePipe){ } @HostListener('document:mousemove',['event']) mouse(e){ this.currentMinute=new Date().getMinutes(); this.ad

我试图调用ngOnInit中的事件方法

    export class AppComponent  {
  currentMinute;addedMinute;mousemove
    constructor(private datePipe: DatePipe){ }
  @HostListener('document:mousemove',['event'])
mouse(e){
 this.currentMinute=new Date().getMinutes();
  this.addedMinute=new Date().getMinutes()+2;
}

  ngOnInit(){
//here i want to display this.currentMinute
}

只是我试过这样,但它给出了未定义的。如何在ngOnInit中调用事件方法。

您无法可靠地执行此操作。创建组件后,设置事件侦听器(
@HostListener
),框架调用
ngOnInit
。侦听器将仅对您指定的事件作出反应(在您的示例中为
document:mousemove
)。如果需要此值,则需要在组件创建(调用构造函数)和调用
ngOnInit
之间触发事件,正如我所解释的,这两个过程之后立即调用。这几乎是不可能的

    export class AppComponent  {
  currentMinute;addedMinute;mousemove
    constructor(private datePipe: DatePipe){ }
  @HostListener('document:mousemove',['event'])
mouse(e){
 this.currentMinute=new Date().getMinutes();
  this.addedMinute=new Date().getMinutes()+2;
}

  ngOnInit(){
//here i want to display this.currentMinute
}
在您的情况下,解决方法非常简单:只需在
ngOnInit
中执行与在
@HostListener
中相同的工作:

export class AppComponent  {
    public currentMinute:number;
    public addedMinute:number;

    constructor(private datePipe: DatePipe){ }

    @HostListener('document:mousemove',['event'])
    public mouse(e):void {
        this.setDates();
    }

    public ngOnInit():void {
        this.setDates();

        // Here this.currentMinute and this.addedMinute are defined now
    }

    private setDates():void {
       this.currentMinute=new Date().getMinutes();
       this.addedMinute=new Date().getMinutes()+2;
    }
}

你想解决的具体问题是什么。这听起来像是个XY问题。我也不明白你所说的“调用事件的函数”是什么意思。我想从save(event)调用ngOnInit中的事件。“调用事件”到底应该做什么?重复你在问题中已经说过的不会澄清它。“召集活动”没有任何意义。您可以调用一个方法,而不是一个事件。您将在ngOnInit获得
this.currentMinute
取消定义,因为
mousemove
事件尚未触发。。。也许你应该告诉我们你想要实现什么。谢谢你的帮助,非常感谢。