Automated Async Saving in Angular 2 using Typescript

I am currently working on implementing an autosave feature in TypeScript. The main objective is to automatically save any text input by the user every 10 seconds to prevent loss of data in case of a page crash or accidental closure. I aim to initiate the autosave functionality immediately after the page has fully loaded.

Here is a snippet of the code I have written:

ngAfterViewInit() {
    this.autoSaveContent();
}

private  autoSaveContent() {
    while (true) {
        if (this.isSaving == false && this.hasContentChanged() == true) {
            this.content.status = 1;
            setTimeout(this.saveContent(), 10000)
        }
    }

}

I am seeking advice on how to execute the code asynchronously. My intention is for this process to run continuously as soon as the page is accessed, ensuring that the content is consistently saved.

Answer №1

Every 10 seconds, setInterval() function will be checking for any changes to the content...

ngAfterViewInit() {
    this.autoSaveContent();
}

private  autoSaveContent() {
    var that = this;
    setInterval(function() {
        if (that.isSaving == false && that.hasContentChanged() == true) {
            that.saveContent();
        }
    }, 10000);
}

When using ES6, you can opt for fat arrow syntax which avoids the need to capture "this" in the closure:

private  autoSaveContent() {
    setInterval(() => {
        if (this.isSaving == false && this.hasContentChanged() == true) {
            this.saveContent();
        }
    }, 10000);
}

Answer №2

It seems like the solution provided should do the trick! The only issue I notice is that you should pass a function reference in the `setTimeout` method instead of directly calling it there.

setTimeout(this.saveContent.bind(this), 10000)

OR

setTimeout(() => { this.saveContent() }, 10000)

Answer №3

Thank you for your feedback, I recently discovered that there is a handy timer feature in Observable. By utilizing this timer, I was able to address the issue efficiently.

ngAfterViewInit() {
    this.isPageActive = true;
    let timer = Observable.timer(10000, 10000);
    let subscription = timer.subscribe(x => this.autoSaveContent());
}

private autoSaveContent() {
    if (this.isSaving == false && this.hasContentChanged() == true) {
        this.content.status = 1;
        this.saveContent();
    }

}

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

Are the Angular2 Material components able to work with previous versions?

For instance, I am currently utilizing Angular2 Material version 5.0.0-rc0. Suddenly, the 5.0.0-rc1 has been released with bug fixes that are essential for me. Is it safe to upgrade the component using npm install --save @angular/material@latest @angula ...

The Angular tutorial for the "Tour of Heroes" is experiencing issues with aligning the heroes' list properly

I am currently working on the Angular tour of heroes tutorial. However, I am facing an issue when trying to display the list of heroes as it appears like this: https://i.sstatic.net/AGnzJ.png It is strange because even though the CSS/HTML/TS code from the ...

Guide to incorporating Bootstrap icons into an Angular application through programming techniques

Have you checked out the official bootstrap documentation for information on how to use their icons? https://i.stack.imgur.com/N4z2R.png I'm currently trying to understand the package and its usage. However, none of the options in the documentation ...

By utilizing custom typeRoots while continuing to export these types alongside the entry point

For my project setup, I employ rollup to bundle an associated index.d.ts (and index.js) for the entrypoint src/index.ts. Within the project structure, there exists a directory named src/types containing multiple .d.ts files. These types are globally acces ...

Implementing Angular Server-Side Rendering (SSR) with .Net Core - enhancing performance by including Cache-Control

In my current project, I am dealing with two types of pages: Angular SSR pages and MVC pages. I am looking to implement a Cache-Control header for only the Angular SSR pages, as they are static pages. Is there a way to achieve this specific caching strate ...

Best practices for receiving messages from SQS in Node.js

I am exploring how to implement SQS in a similar manner as RabbitMQ or Kafka, where we usually set up a listener. However, after going through their documentation, I couldn't find any instructions on how to set up a listener for SQS: Currently, I am ...

Angular 6: Harnessing the Power of RouterLinks

Can you navigate to a different section of another page using the defined ID without having to reload the entire page? ...

Netlify is unable to install a forked npm module due to the failure to retrieve metadata

I recently forked and modified the g-sheets-api module. Here is my version: https://github.com/lpares12/g-sheets-api After making the modifications, I installed it in my web project using the following command: npm install git+https://github.com/lpares12/ ...

Using the useStaticQuery hook outside of a function component is not allowed and will result in an invalid hook call error. Remember to only call

I am currently facing an issue while trying to retrieve values using useStaticQuery from my gatsby-config.js file. Below are snippets of my code. Does anyone have any suggestions on how to resolve this problem? Thank you in advance. Repository: https: ...

Retrieving data using Angular 2's HTTP GET method

I am struggling to properly handle the success and failure responses from my API. When I receive a response in literal form, it gives me an error in the controller. Below is my service code: authentication(userName : string, password:string){ return ...

Tips for Promoting Content Using Offcanvas Navigation Menu

I am currently working on an Angular 12 project that incorporates Bootstrap 5 and NGX-Bootstrap. I am interested in developing a side navigation bar that is initially active but can also be collapsed. I wonder if this could be achieved using the Offcanvas ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...

Sharing Angular 2 modals across different components

My Angular 2 app consists of several components, including a modal component that I added from here. Now, I want to find a way to use the same modal across multiple components. Is it possible to have one modal open when different buttons are clicked in var ...

What is the process for declaring a module in order to perform named imports?

Currently, I am utilizing graphql-tag in my project. The structure of my files is as follows: ./operation.graphql Query User { ... } ./test.ts import { User } from './operation.graphql'; /// Module ''*.graphql'' has no ...

Opening and closing a default Bootstrap modal in Angular 2

Instead of using angular2-bootstrap or ng2-bs3-modal as recommended in the discussions on Angular 2 Bootstrap Modal and Angular 2.0 and Modal Dialog, I want to explore other options. I understand how the Bootstrap modal opens and closes: The display pro ...

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

Using Angular2 to make an HTTP request for a specific JSON file based on the id obtained from a different JSON file

What is the most efficient method for utilizing a HTTP request to retrieve a JSON file based on an ID from another JSON file? Is it preferable to pass the ID from one service to another and use it to fetch the JSON file, or would implementing a single se ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

Clicked but nothing happened - what's wrong with the function?

For my project, I have incorporated tabs from Angular Material. You can find more information about these tabs here. Below is the code snippet I am using: <mat-tab-group animationDuration="0ms" > <mat-tab></mat-tab> < ...

"Learn the process of integrating Javascript files from the Angular assets folder into a specific Angular component or module (such as Angular 2, 4,

I have custom1.js, custom2.js, and custom3.js JavaScript files that I need to load into Angular components component1, component2, and component3 respectively. Instead of adding these files to the index.html globally, I want to load them specifically for e ...