Trouble with updating data in Angular 5 through page reload

Encountered a problem with the home, create, and edit product pages.

After creating and saving data, it redirects to the home page where the latest products are displayed. Unfortunately, the newly created data does not update automatically until the page is manually refreshed.

Are there any tricks to refresh or reload the latest data? Here is my code:

Service

@Injectable()
export class httpServices {
   public current_lang;
   constructor(private http: HttpClient,private _translate:TranslateService) {

   }
   public getCategory() {
        let categories = this.http.get(GlobalVariable.BASE_API_URL+"categories");
        return categories;
   }
   public getSubProjects() {
        let subprojects = this.http.get(GlobalVariable.BASE_API_URL+"subprojects");
        return subprojects;
   }

   public getProductList() {
     //return this.http.get("./assets/data/productlist.json");     
     let products = this.http.get(GlobalVariable.BASE_API_URL+"products/date");
     return products;
   }
} 

Home ts

ngOnInit(){
    this._httpService.getCategory().subscribe(data=>{

      this.categoryFilterArray = data;
    });

    this._httpService.getSubProjects().subscribe(data=>{

      this.subProjectFilterArray = data;
    });

    this._httpService.getProductList().subscribe(data=>{

      this.projectListData = data;

    });

  }

Home HTML

<div  *ngFor="let item of projectListData | filter : searchText">

                  <div class="project-wrap" [routerLink]="['/admin/project-detail/', item.id]">
                <div class="project-img">
                  <img src="{{apibaseurl}}images/product_{{item.id}}.png?{{timestamp}}" alt="project" />
                </div>  
                <div class="project-content">
                   <!--  <h3 tooltip="{{item.name}}" [tooltipDisabled]="false" [tooltipAnimation]="false"
                  tooltipPlacement="top">{{item.name}}</h3>-->
                  <h3 title="{{item.name}}">{{item.name}}</h3>
                  <label><b>{{ 'SUB_PROJECT' | translate}}:</b> {{ item.subProject.name | translate}}</label>
                  <label><b>{{ 'PROJECT_CATEGORY' | translate}}:</b> {{ item.category.name | translate}}</label>
                  <label><b>{{ 'STATUS' | translate}}:</b> {{ item.status | translate}}</label>
                </div> 
              </div>      
            </div>

Create

this.http.post(GlobalVariable.BASE_API_URL+'product/create', body)
            .subscribe( resultArray => {             
                this.successMsg = "Product created successfully." ; 
                setTimeout((_router: Router) => {
                    this._router.navigate(['admin/home']);
                }, 2000);
            }

Answer №1

It's possible that the issue you're experiencing is related to browser caching. One way I managed to solve a similar problem was by including a timestamp as a search parameter in each call. Below is a snippet from my basic data service:

import { Headers, Http, RequestOptionsArgs, Response, ResponseContentType, URLSearchParams } from '@angular/http';

// RequestOptions object for GET requests
private requestOptions: RequestOptionsArgs = {};

// URLSearchParams object for POST, PUT, and DELETE requests
private requestUrlSearchParams = new URLSearchParams();

// Method to add timestamp to search params before each backend call
setSearchParamsTimeStamp() {
    this.requestUrlSearchParams.set('timestamp', (new Date()).getTime().toString());
    this.requestOptions.search = this.requestUrlSearchParams;
}

// Generic getter method
public getData<T>(url: string, logText: string): Promise<T> {
    // Set the latest timestamp before making the call
    this.setSearchParamsTimeStamp();

    return this.http.get(url, this.requestOptions)
        .toPromise()
        .then(response => (response.json() as T))
        .catch(this.handleError);
}

I hope this solution helps you with your issue.

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

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

Dealing with a series of challenging npm problems consecutively

npm WARNING: Deprecated Usage Please note that global '--global' and '--local' configurations are now deprecated. Please use '--location=global' instead. Error Code: ERESOLVE Unable to resolve dependency tree. While reso ...

Having difficulty creating a TypeScript function

I've encountered a TypeScript error that has left me puzzled: src/helpers.ts:11:14 - error TS2322: There's an issue with this piece of code and I can't quite grasp it: Type '<T extends "horizontal" | "vertical" | undefined, U extends ...

Unregistered outlet name unrecognized

I am currently working on developing a tabs component within one of my components, utilizing named outlets for this purpose. At the moment, I have my default outlet set up to display each page, and I would like to incorporate a named outlet within one of ...

What causes TypeScript to narrow the type when a return statement is present, but not when it is absent?

I am facing an issue with this script: type Input = string function util(input: Input) { return input } function main(input: Input | null) { const isNull = input === null if (isNull) { return 'empty string' } inpu ...

Broadcasting TypeScript Data Structures via Socket.IO

In my Typescript code, I have created a basic User class as shown below: export class User { constructor(public id: string); } When I emit a message from my socket.io server, I include an instance of the User class like this: var user = new User(&ap ...

When attempting to run the yarn build dist command, an error of type TypeError is encountered, stating that it is not possible to set the constructor property

Upon executing the following command in a GitHub workflow, I encountered this error: npm-run-all -p types transpile @internal_package: $ swc src --out-dir dist @internal_package: /home/runner/work/repo-name/repo-name/node_modules/ttypescript/lib/loadTypesc ...

Angular class requires multiple class members and validators for MatSelection List to be bound with Formbuilder

Could you please guide me on how to connect the Google Angular Materials mat-selection-list with the FormBuilder? We have the following class and are attempting to utilize Reactive Form Builder for this purpose. While we are aware of how to link data class ...

Tips for dynamically updating the included scripts in index.html using Angular 2

As I work on incorporating an Angular website into a Cordova app, one challenge I face is getting the Cordova app to load the Angular remote URL. The index.html file for the Angular site includes the cordova.js file, which is specific to each platform - ...

Using iframes in Angular 2/4's index.html

I'm currently working on an angular application and for session management, I've implemented OpenID Connect Session Management. I am attempting to inject iframes into the application. I need to include an iframe in my index.html as follows: < ...

Angular 7 makes it a breeze to move elements using the drag and

Is there a way to drag and drop elements from an expansion panel while still keeping them displayed within the panel after being dropped? I am looking for Angular 7 code to achieve this functionality. Your assistance is much appreciated. I attempted to dr ...

TypeScript error message: "The 'new' keyword cannot be used with an expression that does not have a call or construct signature."

Encountered a problem with intersection types in TypeScript... There are three type aliases: Prototype<T> - representing an object or class with a prototype property. DefaultCtor<T> - representing an object or class with a default construct ...

Unable to open modal externally without encountering an error in MaterializeCSS

I'm currently facing an issue with a standard modal that pops up at the bottom of the page. I have a function that generates multiple components on the page, each with a 'play' button. When this button is clicked, it triggers a function pass ...

Choosing the right design strategy for an Angular2 application featuring dynamically loaded components

Within my application, the initial page allows users to choose an item from a list based on their previously saved preferences. This selection then updates the view to display the chosen functionality or page. Each of these pages has unique configurations ...

What is the best method to retrieve the value of a cell in a different cell within the same row in an Angular Material Data-Table?

I am working with an Angular Material Data Table that has four columns. In every row, the last cell contains a button with an on-click function attached to it. I need to pass the value from the first cell ("Name") as a parameter in the corresponding button ...

Troubleshooting: Angular2 fails to send HTTP GET requests

There seems to be an issue with the code provided in (A) where it fails to send its HTTP request when `test()` is called. In contrast, the similar code in (B) functions properly. Do you have any insights into what might be causing this problem? I can confi ...

Angular 2: Enhancing Textareas with Emoji Insertion

I am looking to incorporate emojis into my text messages. <textarea class="msgarea" * [(ngModel)]="msg" name="message-to-send" id="message-to-send" placeholder="Type your message" rows="3"></textarea> After entering the text, I want the emoj ...

Different Ways to Customize Button Click Events in Angular 9 Based on Specific Situations

In my Angular 9 web application development, I frequently need to integrate Bootstrap Modals like the example below: <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="do ...

How can I set the default bindLabel for a dropdown in @ng-select/ng-select when the self change event occurs in Angular

I have a scenario where I need to set the default value to null in the ng-select. If the user selects an option from the dropdown first, then on the change event it should check if the Amount model is not null or blank. If the Amount model is blank, then ...

Steps to change the default sort arrow icon in ag-grid to a custom SVG icon

Would greatly appreciate any assistance with this. I have reviewed the documentation, but it's still unclear to me. ...