Determining Refresh Status in Angular Application

Does Angular provide a method to determine if the browser has been refreshed? I need to verify whether the page has been refreshed or not, as I want to run a function only when the value is false.

In my ngOnInit function, I have the following code:

pageIsRefreshed: Boolean;

ngOnInit() {
  this.subscription.pipe().subscribe(res=> {
    if(!pageIsRefreshed) { 
      dofunction();
    }
  })
}

However, I am struggling to find a solution to identify if the page has been refreshed or not.

Answer №1

It seems that checking if a person has refreshed the page using Angular alone is not feasible.

One approach could be to set up a session when the visitor lands on the page for the first time, and then monitor this session to determine if the page has been refreshed.

ngOnInit() {
    this.subscription.pipe().subscribe(res => {
        const isPageRefreshed = sessionStorage.getItem('isPageRefreshed');
        
        if (isPageRefreshed === 'true') { 
            doFunction();
        } else {
            sessionStorage.setItem('isPageRefreshed', 'true');
        }
    })
}

Remember to clear the session once it is no longer needed.

Answer №2

One way to utilize Router in Angular is shown below:

constructor(private router: Router) {
  this.subscription = router.events.subscribe((event) => {
    if (event instanceof NavigationStart) {
      browserIsRefresh = !router.navigated;
    }
  });
}

The value of "browserIsRefresh" will be false when the router starts and true after the first navigation.

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

Encountering Error 203 while trying to establish a connection between Angular and Django Rest Api

I'm currently working on a project that involves creating a contacts system, but I've been encountering errors when trying to list them. Interestingly, I can successfully perform CRUD operations using Postman with the API. One of the messages I ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Is there a method in TypeScript to create an extended type for the global window object using the typeof keyword?

Is it possible in TypeScript to define an extended type for a global object using the `typeof` keyword? Example 1: window.id = 1 interface window{ id: typeof window.id; } Example 2: Array.prototype.unique = function() { return [...new Set(this)] ...

Emphasize a word in a Typescript text by wrapping it in an HTML tag

I've been experimenting with using HTML tags within TypeScript to highlight specific words in a sentence before displaying the sentence in HTML. Despite searching on StackOverflow for various solutions, I haven't been able to find one that works. ...

How to assign multiple values within nested for loops in Angular 6

I am facing an issue with my template file where I have two loops. I am attempting to bind the second value using the first loop value, but I am encountering an error. <tr *ngFor="let splitdata of mf.data"> <td *ngFor="let slitup of searchFie ...

Restrict the number of items in a list in Angular 2 to a

I need help structuring a list of material cards in my application. The list can potentially have a large number of elements, so I want to limit it to showing only 5 items at a time and provide an option for the user to navigate through additional elements ...

Ways to effectively test public functions in Typescript when using react-testing-library

I have come across the following issue in my project setup. Whenever I extend the httpService and use 'this.instance' in any service, an error occurs. On the other hand, if I use axios.get directly without any interceptors in my service files, i ...

Using aliased imports is no longer an option when setting up a new TypeScript React application

Upon creating a new React-typescript app using the following command with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3143545052457100061f011f03">[email protected]</a> and <a href="/cdn-cgi/l/email-protectio ...

Encountering a permission issue while trying to execute npm install -g @angular/cli command

I recently started using Angular and am working on a new project. However, when I try to execute the following command: npm install -g @angular/cli I encounter the error message below: npm WARN checkPermissions Missing write access to /usr/local/lib/no ...

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

What is the best way to write a function in typescript that verifies whether the argument extends a type argument and then returns the argument?

I need to create a function that checks if the argument's type extends a specific type variable and then returns the argument. Something like this: declare function checkType<T, X extends T>(argument: X): X However, TypeScript gives an error wh ...

Using TypeScript: creating functions without defining an interface

Can function props be used without an interface? I have a function with the following properties: from - HTML Element to - HTML Element coords - Array [2, 2] export const adjustElements = ({ from, to, coords }) => { let to_rect = to.getBoundingC ...

The input field cannot accommodate the lengthy value in the Mat Select option

When a user selects a value in my mat select, it doesn't display well in the selection box. The text wraps when the selection is opened, but once a choice is made, it gets cut off without proper spacing between the ellipses and the dropdown arrow. Th ...

Pass JSON data from Angular service to component

I have encountered a challenge while trying to pass JSON data from my API service to a component without directly subscribing in the component. The issue arises when attempting to access the data outside of the subscription block, as it returns something u ...

Beginning external plugin in Angular 4 application

Is it possible to incorporate an external plugin into an Angular 4 application? I am looking to utilize the niceScroll plugin for a scrollable div, which is defined within a component. <div class="d-flex" id="scrollable"> <app-threads-list> ...

Having trouble with passing data using @Input in Angular 5

My goal is to pass a value from app.component.ts named user and assign it to the property of the userComponent called user. Below are the code snippets: app.component.ts import { Component } from '@angular/core'; @Component({ selector: &apo ...

When a webpage is moved, the globalProperties variable of "vue3 typescript" is initialized to null

main.ts const app = createApp(App) .use(router) .use(createPinia()) .use(vuetify) .use(vue3GoogleLogin, googleLogin) const globalProps = app.config.globalProperties; globalProps.isDebugMode = true; vue-shim declare ...

Issue with assigning objects to an array

I'm currently working on a TypeScript application and I've run into an issue with assigning values. Here are the interfaces for reference: export interface SearchTexts { SearchText: SearchText[]; } export interface SearchText { Value: st ...

Discover the best way to cycle through bootsrap modal dialogs using angular

Within my component.ts file, there exists an array: dummyData = ['1', '2', '3']; The objective is to iterate through this array and generate 3 modals displaying values 1, 2, and 3 respectively. Here's a snippet of the ...

The Angular overlay panel remains open consistently

I recently developed an Angular component similar to p-overlaypanel, but I'm facing an issue where it remains open for every item I click. What I actually want is for only one overlay panel to be clicked and shown at a time - if I click on another ove ...