0

I'm attempting to initiate repeated client-side action within OnInit of an Angular 4 component using an IntervalObservable. The application uses ASP.NET Core.

The observable subscription is executed. However, server-side prerendering in Microsoft.AspNetCore.NodeServices appears to be executing the subscription -- never returning the rendered page to the browser.

What am I doing wrong here? Below are the steps to reproduce. In this sample I'm just trying to console.log a heartbeat in the browser.

Steps to reproduce

  1. Create and cd into a new directory.
  2. Run dotnet new angular.
  3. Run npm install.
  4. Replace the contents of ClientApp/app/components/home/home.component.ts with the code snippet below.
  5. Run dotnet run and go to http://localhost:5000.
    import { Component, OnInit } from '@angular/core';
    import { IntervalObservable } from "rxjs/observable/IntervalObservable";

    @Component({
        selector: 'home',
        templateUrl: './home.component.html'
    })
    export class HomeComponent implements OnInit {
        ngOnInit(): void {
            IntervalObservable.create(1500).subscribe((iteration:number)=>console.log(iteration));
        }
    }

When the request comes in, the debug console begins reporting the iteration, as shown in the code snippet. The page renderer times out and eventually return an error page, but the IntervalObservable subscription continues to iterate in the debug console.

Gnosian
  • 334
  • 8
  • 16

1 Answers1

0

I found a resolution using the technique shown in https://stackoverflow.com/a/46893433/402726.

Essentially, we use the platform functions provided Angular to determine if we're executing in the browser and, if so, run the in-browser heartbeat.

Below is an updated form of the question snippet implementing the fix.

import { PLATFORM_ID, Component, Inject, OnInit } from "@angular/core";
import { isPlatformBrowser } from "@angular/common";
import { IntervalObservable } from "rxjs/observable/IntervalObservable";

@Component({
    selector: "home",
    templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
    private isRunningInBrowser: boolean;
    constructor( @Inject(PLATFORM_ID) platformId: string) {
        this.isRunningInBrowser = isPlatformBrowser(platformId);
    }
    public ngOnInit(): void {
        if (!this.isRunningInBrowser) return;
        IntervalObservable.create(1000).subscribe(() => console.log("on an interval"));
    }
}
Gnosian
  • 334
  • 8
  • 16