جاوااسکریپت - زمانبندی پیشنمایش Angular با setInterval() به پایان میرسد


من یک پروژه Visual Studio 2017 با .NET Core 2.0 و قالب Angular دارم. پیشپردازش Angular زمانی که یکی از خطوط «this.SetUpRefreshInterval()» را از کامنت خارج میکنم، زمانی که تمام میشود تایماوت میشود. برنامه خطای «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.» را برمیگرداند. ایدهای دارید؟

در اینجا کد مؤلفه آورده شده است:

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();
    }
}

من همچنین تلاش کردم از Observable.timer استفاده کنم و همان نتیجه را گرفتم:

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

به عنوان راهحل موقت، از پیشنهاد کریشناناونی استفاده کردم و این تغییر را اعمال کردم که کار میکند:

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 بپیچید تا پیشنمایش نشود