Refreshing a page in Angular 4/5 using TypeScript

I am currently working on a single-page application that utilizes routes for navigation:

this.router.navigate(['/customer-home'], { skipLocationChange: true });

While on the customer home page, I have a feature to add a new customer via a REST call. Once the customer is successfully added, I want the page to automatically refresh and display the updated /customer-home view.

My current approach is as follows:

addNewCustomer(customer) {
    this.dataService.postEntity('customers', customer);
    location.reload();
}

The issue with using location.reload is that it refreshes the page and redirects me to the home page.

I checked the console log for the location:

Location {replace: ƒ, assign: ƒ, href: "http://localhost:4200/", ancestorOrigins: DOMStringList, origin: "http://localhost:4200", …}

Is there a way for me to reload the page and data without explicitly refreshing the location in the browser's address bar?

On a side note, I attempted redirecting to another component and then returning to the current one, but this method failed to reload the data and show the newly added customer details.

Answer №1

Utilizing Location.reload within a Single Page Application goes against the core principles of SPAs.

It appears as though you are attempting to refresh the page in order to retrieve updated data from your server.

The responsibility of loading data should not fall on the Router. Instead of triggering a page reload, consider fetching the data upon insertion or during the callback function of your postEntity method.

Alternatively, rather than making another request for data, consider simply adding the Entity to the existing array of customers or whatever storage mechanism you are using.

Answer №2

If you are looking to redirect or reload to your customer page, one way to achieve this is by utilizing the router service.

addNewCustomer(customer) {
    this.dataService.postEntity('customers', customer);
    this.router.navigate(['/customer-home']);
}

However, it may be beneficial to consider using Observables or Promises to reload your data instead of refreshing the entire page, as suggested by others. Below is an example of how you could implement an Observable:

addNewCustomer(customer) {
    this.dataService
        .postEntity('customers', customer)
        .subscribe(
            update => this.customer = update;
            err => console.log(err); 
        )
}

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

Component opens MatSnackBar in various styles

I've been seeking a method to achieve the following: incorporating a custom SnackBar for displaying notifications. After consulting the official documentation (here), I successfully created a basic Snackbar with customized settings. this.snackBar.ope ...

What is the best way to refresh a personalized form element using Angular?

I have developed a custom form control with validation that utilizes a standalone FormControl to manage the value and perform certain validations. Is there a method in Angular to reset the inner FormControl when the control is being reset from another For ...

What benefits do declaration files offer compared to sources in TypeScript?

When developing and releasing a library using TypeScript, there are 2 approaches: One option is to generate declaration files d.ts along with the bundled JavaScript file and then specify it in package.json with: "types": "./dist/mylib.d.ts" Alternativel ...

Issue with absolute import in React TypeScript application

An error occurs when trying to import a module, displaying the following message: Compiled with problems: × ERROR in ./src/App.tsx 5:0-33 Module not found: Error: Can't resolve 'routes' in 'F:\Tamrinat\Porfolio\microsite ...

Manipulate dropdown choices by interacting with the dropdown form control in an Angular application

Is there a way to dynamically set options based on the form control name in Angular? For example, if we have a countries dropdown, we typically assign all countries to a specific variable and iterate over them using *ngFor. I am looking to change the opt ...

Collaborate on sharing CSS and TypeScript code between multiple projects to

I am looking for a solution to efficiently share CSS and TS code across multiple Angular projects. Simply copy-pasting the code is not an ideal option. Is there a better way to achieve this? ...

Delivering an Angular2 application from a base URL using Express

I currently have an Angular2 application running alongside a simple express server. Is there a way to only display my application when a user navigates to a specific route, like '/app' for example? If so, how can this functionality be implemented ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

Tips for implementing assertions within the syntax of destructuring?

How can I implement type assertion in destructuring with Typescript? type StringOrNumber = string | number const obj = { foo: 123 as StringOrNumber } const { foo } = obj I've been struggling to find a simple way to apply the number type assertio ...

Avoid using dot notation with objects and instead use `const` for declaring variables for more

interface obj { bar: string } function randomFunction() { let foo: obj = { bar: "" } foo.bar = "hip" } let snack: obj = { bar: "" } snack.bar = "hop" Upon transcompiling, a warning from tslint pops up: Identifier 'foo' is never reassi ...

Receiving a Promise<fullfield> as a result

I have a situation where I am adding several promises to an array: const apiCallsToMake = []; apiCallsToMake.push(this.getDataFromUnsplash(copyInputParams)); apiCallsToMake.push(this.getDataFromPexels(copyInputParams)); apiCallsToMake.pu ...

The form will not appear if there is no data bound to it

Can anyone help me with displaying the form even when the data is empty in my template? <form class="nobottommargin" *ngIf="details" [formGroup]="form" (ngSubmit)="onSubmit(form.value)" name="template-contactform"> <div class="col-sm-12 nopad ...

Angular 2: How to Avoid Exceeding Maximum Call Stack Size with Eager Loading

I'm facing an issue with preloading all of my child route modules. In my root routing module, I have the following configuration: RouterModule.forRoot(appRoutes, { preloadingStrategy: AppCustomPreloader }) The structure of AppCustomPreloader is as f ...

What is the best way to invoke a method in a child component from its parent, before the child component has been rendered?

Within my application, I have a parent component and a child component responsible for adding and updating tiles using a pop-up component. The "Add" button is located in the parent component, while the update functionality is in the child component. When ...

I encountered a TypeScript error in React Native when attempting to use "className" with TypeScript

Although I've been using React for a while, React Native is new to me. I recently started using tailwind with import { View, Text } from "react-native"; import React from "react"; export default function Navigation() { return ...

Setting up Typescript error handling for next-auth getProviders configuration

I recently started learning Typescript and came across a tutorial using next-auth. However, I encountered an error while following the tutorial with Typescript when using the getProviders function. https://i.stack.imgur.com/H5LaL.png https://i.stack.imgu ...

The potential object null may lead to an absence of the 'value' property in the type 'EventTarget'

I am facing a problem that I am unable to resolve. The error in my HTML reads: Object is possibly 'null' and Property 'value' does not exist on type 'EventTarget'. HTML <select [(ngModel)]="selectedProvincia" (ch ...

Utilize the canActivate method to decide when to display a specific hyperlink

I'm facing a challenge with my AuthGuard implementation using CanActivate to decide whether or not to display a link. Despite my efforts, I am unable to properly check the canActivate property of the Route. Here is the function I created: TypeScript ...

Heroku build is reporting that it cannot locate the `@types` in the package.json file

Encountered Heroku Build Error - TSError: ⨯ Struggling to compile TypeScript: - src/server.ts(1,38): error TS7016: File declaration for module 'express' not found. '/app/node_modules/express/index.js' is implicitly of type 'any&a ...

Checkbox selections persist when navigating between pages

I am currently working with Angular 9 and I have a list of checkboxes that need to default to true when displaying certain data. If one of these checkboxes is unchecked, it should trigger the display of specific information. The issue I am facing is that o ...