ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation:

It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error:

Exception: Call to Node module failed with error: Prerendering failed because of error: ReferenceError: document is not defined at new DocumentInterruptSource

Is there a way to make ng2-idle work with pre-rendering? Are there any workarounds or alternative ways to implement idle timeout warning and keep alive ping to the webserver?

Let me know if you need to see any code. It's exactly the same as in the provided link and it works without pre-rendering.

Thank you for your time.

Answer №1

One issue arises when the server attempts to render client elements, which is not feasible. To address this problem, you need to instruct the server not to render these specific parts.

One way to achieve this is by using PLATFORM_ID from Angular core. By utilizing an if statement such as "don't do this on the server", you can prevent server-side rendering.

For instance, consider creating a custom auto logout feature with the use of addlistener. In the provided example, the process begins in ngoninit with If(isPlattformBrowser), ensuring that it operates exclusively on the browser and not the server. Similarly, when implementing Idle, ensure the action triggers within the if(isPlattformBrowser) condition.

To implement this functionality, create a component following the example provided and include your auto-logout component in the app.component.html file as shown below:

<router-outlet name="header"></router-outlet>
<router-outlet></router-outlet>

<app-auto-logout></app-auto-logout>

(replace "your component" with the actual name of your component) This setup ensures that the auto-logout feature is activated across all components. Since app.component loads first and subsequent components load within it, any actions defined in app.component will be applied universally.

import {Component, ElementRef, Inject, OnInit, ViewChild} from '@angular/core';
import {AuthService} from '../../../../services/auth.service';


import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
declare var $:any;
@Component({
  selector: 'app-auto-logout',
  templateUrl: './auto-logout.component.html',
  styleUrls: ['./auto-logout.component.scss']
})
export class AutoLogoutComponent implements OnInit {

  warnTimeout: any;
  logoutTimeout: number;
  // warn: number;
  // logout
  setState: string;
  events = [
    "load",
    "mousemove",
    "mousedown",
    "click",
    "scroll",
    "keypress"
  ];
  countdown: any;
  interval: any;
  constructor( private authService: AuthService,
               @Inject(PLATFORM_ID) private platformId: Object) {


  }
  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
    this.warn = this.warn.bind(this);
    this.logout = this.logout.bind(this);
    this.resetTimeout = this.resetTimeout.bind(this);

      for (var i in this.events) {
        window.addEventListener(this.events[i], this.resetTimeout);
        console.log('Event registered');
      }

    this.setTimeout();
    }
    this.countdown=15;
  }
  setTimeout() {
    this.warnTimeout = setTimeout(this.warn, 600000);

    this.resetTimeout();
  }
  
  // Additional functions omitted for brevity

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What strategies can I implement to ensure my modal dialog box remains responsive? Adjusting the window size causes the modal box to malfunction and lose its structure

Whenever I adjust the size of the browser window, the elements inside the modal box become misaligned. HTML <div class='modal'> <div class='modal-content'> </div> </div> Below is the CSS for the modal ...

Uploading Massive Form Data Using Angular JS

After spending countless hours on this project, I still can't figure out how to post data into a table using JavaScript objects. While I can easily work with smaller data sets, I'm struggling with handling multiple nested objects. EDIT: ...

What is the process for implementing a security rule for sub-maps with unique identifiers in Firebase?

I am looking to implement a security rule ensuring that the quantity of a product cannot go below zero. Client-side request: FirebaseFirestore.instance .collection('$collectionPath') .doc('$uid') .update({'car ...

Angular is unable to eliminate the focus outline from a custom checkbox created with Boostrap

Have you noticed that Angular doesn't blur out the clicked element for some strange reason? Well, I came up with a little 'fix' for it: *:focus { outline: none !important; } It's not a perfect solution because ideally every element sh ...

Encountering a glitch when attempting to run Bootstrap 4 on an Angular 6 Application

After installing Bootstrap 4 using Angular CLI, I encountered an error when running the application. To resolve this issue, I made changes to the angular.json file: "styles": [ "src/styles.css", "../node_modules/bootstrap/dist/css/bo ...

Angular - Display shows previous and current data values

My Angular application has a variable called modelResponse that gets updated with new values and prints them. However, in the HTML, it also displays all of its old values along with the new ones. I used two-way data binding on modelResponse in the HTML [( ...

Angular 6 and Typescript: How to Map Objects in Arrays within Arrays

We currently have two arrays named speisekarte (consisting of 10 objects) and essensplan (containing 8 objects). const speisekarte = [ { id: 11, name: 'Kabeljaufilet', price: 3.55, type: 'with fish' }, { id: 12, name: 'Spaghet ...

Receive the deleted entry upon clicking the thead | Error发

Is there a way to permanently delete a row in a datatable? If I delete all the rows, I would like the datatable to display the default message of "No data available". I have attempted some POST requests : But with no success. DataTables remove row butto ...

Stop focusing on mat-select after a selection is made

I am encountering an issue with the following code in my .html file: <mat-form-field> <mat-select #selector(selectionChange)="onSelectionChange($event.value)"> <mat-option *ngFor="let test of tests" [value]="test"> </ma ...

Node.js used to create animated gif with unique background image

As I navigate my way through the world of node.js and tools like express and canvas, I acknowledge that there might be errors in my code and it may take me some time to grasp certain concepts or solutions. My current project involves customizing a variati ...

Is it possible to transform this nested promise into a chain instead?

This situation is just a scenario | then (items) | then (items, actions) getItems() | getActions(for:items) | apply(actions -> items) :promise | :promise | model <= items | | :sync ...

Adjust alterations in a Vue Component to apply to separate routes

I have a Filter tab component that I use in various routes. When I click on a tab, it becomes active. After clicking on one tab, I want it to remain active in other routes as well. How can I achieve this? Any suggestions or articles would be greatly apprec ...

Exploring the depths of Angular's nested formGroups

I am facing a challenge in updating my form with data. There is a nested formGroup within another formGroup, and despite receiving the data, the form does not update; it remains empty. The data is visible in the logs, indicating an issue with the form&apos ...

Is there a way to retrieve time data from a different server through AJAX?

I am in need of obtaining time information from an online source, whether it be an NTP server, JSON time server, or simply an HTTP Header. The precision is not important to me, but the requirement is that I must get the time from an online source. Unfortun ...

Error: Value Loop Detected in AngularFire Document ID

I encountered a "Cyclic Object Value" Error while working on an Angular Project with AngularFire. As a beginner with Firebase, I haven't been able to find a straightforward solution to this issue. The error arises when I query a collection in my Fire ...

Two lines in ChartJS with distinct fill gradients for each

I am facing an issue with ChartJS version 2.6 in my Ionic 3/Angular 4 app. I have set up a line chart config with 2 datasets, but I am struggling to apply individual fill gradients to each line. What I am aiming for is something like this: https://i.stac ...

I need to know how to create a patch request in Vue.js and simultaneously modify the marks input for specific individuals by using v-model

Hello there, I am currently developing a student assessment input form using vuejs, express, and mongoDB. The backend API is complete and functioning properly when tested with postman. Here is the code: // UPDATE MARKS router.patch('/:studentId' ...

Enhancing Efficiency with Laravel 5: Updating Multiple Data Entries

My Simple Todo App lacks the ability to persist multiple record updates simultaneously. The client-side version can be found here: http://codepen.io/anon/pen/bVVpyN Whenever I perform an action, I send an HTTP request to my Laravel API for data persistenc ...

Transferring information between components within AngularJS

export class AppComponent { title = 'shopping-cart'; ngOnInit() { } images = [ { title: 'At the beach', url: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?ixlib=rb-4.0.3&ixid=MnwxMjA ...

How can I transform a JSON object into a series of nested form fields?

Can anyone suggest a reliable method for converting a JSON object to nested form fields? Let's consider the following JSON object: {'a':{'b':{'c':'1200'}}}, 'z':'foo', 'bar':{&apo ...