简体   繁体   English

使用setInterval()进行角度预渲染超时

[英]Angular prerendering times out with setInterval()

I have a Visual Studio 2017 .NET Core 2.0 project with Angular template. 我有一个带有Angular模板的Visual Studio 2017 .NET Core 2.0项目。 Angular prerendering times out when I uncomment either of the "this.SetUpRefreshInterval()" lines below. 当我取消注释以下任一“ this.SetUpRefreshInterval()”行时,角度预渲染超时。 The app returns error "NodeInvocationException: Prerendering timed out after 30000ms because the boot function in 'ClientApp/dist/main-server' returned a promise that did not resolve or reject. Make sure that your boot function always resolves or rejects its promise." 该应用程序返回错误“ NodeInvocationException:30000毫秒后预渲染超时,因为'ClientApp / dist / main-server'中的启动功能返回了无法解决或拒绝的承诺。请确保您的启动功能始终可以解决或拒绝其承诺。” Any ideas? 有任何想法吗?

Here's the component code: 这是组件代码:

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

@Component({
selector: 'app-currentdatetime',
templateUrl: './currentdatetime.component.html',
styleUrls: ['./currentdatetime.component.css']
})
export class CurrentDateTimeComponent implements OnInit {
    private currentDateTime: Date;

    constructor() {
        this.refreshDate();
        //this.setUpRefreshInterval();
    }

    get currentDateFormatted(): String {
        return this.currentDateTime.toLocaleDateString();
    };

    get currentTimeFormatted(): String {
        return this.currentDateTime.toLocaleTimeString(); 
    };

    ngOnInit(): void {
        //this.setUpRefreshInterval();
    }

    private setUpRefreshInterval(): void {
        setInterval(() => {         
            this.refreshDate();
        }, 1000);
    }

    private refreshDate(): void {
        this.currentDateTime = new Date();
    }
}

I also tried using Observable.timer and got the same result: 我也尝试使用Observable.timer并获得了相同的结果:

    private setUpRefreshInterval(): void {
        let timer = Observable.timer(0, 1000);
        timer.subscribe(t => this.currentDateTime = new Date());
    }

As a workaround, I used Krishnanunni's suggestion and made this change, which works: 作为解决方法,我使用了Krishnanunni的建议并进行了更改,该更改有效:

import { Component, OnInit, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { PLATFORM_ID } from '@angular/core';

constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    this.refreshDate();
}

ngOnInit(): void {
    // setting up the refresh interval caused a timeout in prerendering, so only set up interval if rendering in browser
    if (isPlatformBrowser(this.platformId)) { 
        this.setUpRefreshInterval();    
    }        
}

将间隔代码包装在isPlatformBrowser条件中,以便不预先渲染

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM