Display notification if the request exceeds the expected duration

Is there a way to display a message when a request is taking too long? For instance, if the request exceeds 10 seconds in duration, I want to show a message asking the user to wait until it finishes.

fetchData(url, requestParams) {
  return this.restService.get('url', requestParams)
}

displayMessage(duration) {
 setTimeout( () => {
     console.log("The request is taking more than 10 seconds. Please be patient.")
 }, duration)

}

I attempted using setTimeout but did not achieve the desired outcome.

Answer №1

The solution appears to be Intercept, which is a great fit for this particular scenario.

 requestTimeout;

displayAlert(time) {
    clearTimeout(this.requestTimeout);
    this.requestTimeout = setTimeout(() => {
        console.log("the request is taking more than 10s, please wait.");
        }, time)
}
  
intercept(req: HttpRequest<any>, next: HttpHandler) {
    this.displayAlert(10000);

    return next.handle(authReq).pipe(
        tap(resp => {
            if (resp instanceof HttpResponse) {   
                clearTimeout(this.requestTimeout);
            }
        })
    );
  };  

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

I have an Observable but I need to convert it into a String

Seeking assistance with Angular translation service and Kendo.UI components. In the Kendo.UI documentation, it mentions the use of MessageService for component translation implementation. To achieve this, an abstract class must be extended containing a m ...

Angular enables the use of multiple instances of a service from the parent component to the child component

I recently came across this discussion: Utilizing multiple instances of the same service. Can one utilize multiple instances of a service from parent to children? For instance, imagine having an ElementService in the ParentComponent with 2 separate instan ...

What is the best approach to implement runtime configuration in Angular 15, ensuring that values can be provided in AppModule imports as well?

After two days of brainstorming, I am still struggling to figure out a way to read a config.json file located in my assets folder. I attempted to read this file during the bootstrapping process in main.ts so that I could use the values in my AppModule lik ...

Previewing images with Dropzone through extending file types

Want to display an image preview before uploading using dropzone. Attempting to access the images by calling file.preview but encountering the error "it does not exist on type File." Dropzone extends the file type with a preview?: string. How can I access ...

Having trouble with browser freezing when using array push in Angular 4? Looking for a solution to fix this issue?

In my logsCompoment.ts file, there is an array called logs where I store new log entries and display them on the HTML page using ngFor directive. I achieve this by handling incoming data in the following manner: this.socket.on('newline', (data) ...

Merge three asynchronous tasks into a single observable stream

I have 3 different observables that I am using to filter the HTML content. Here is the TypeScript code snippet: fiscalYear$ = this.store$.select(this.tableStoreService.getFiscalYear); isLoading$ = this.store$.select(this.tableStoreService.tableSelector ...

Consecutive API requests within React context

When I'm developing locally, I encounter the error message Error: Rendered more hooks than during the previous render. in my application when refreshing the page. I suspect this is happening because I am making two calls within my provider. The first ...

Create typings for object properties in TypeScript

I am inexperienced with TypeScript and am looking to set up types for my object keys. I have explored a few methods to accomplish this, but I am encountering an issue where an error is not triggered when assigning a value of a different type. For example: ...

The primeng MenuItem component does not have a 'command' property and is of type 'never'

I am currently working on implementing a primeng ContextMenu using the Menu Model API. Within the MenuItem object, there is a property named "command" which, to my understanding, should be a function. As I am receiving the available context menu items fro ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...

Troubleshooting problems with resolving deeply nested promises

My approach to utilizing promises has been effective until now. The issue arises when the console.log(this.recipe) returns undefined and console.log(JSON.stringify(recipes)) displays an empty array. This suggests that the nested promises may not be resolvi ...

TypeScript will show an error message if it attempts to return a value and instead throws an

Here is the function in question: public getObject(obj:IObjectsCommonJSON): ObjectsCommon { const id = obj.id; this.objectCollector.forEach( object => { if(object.getID() === id){ return object; } }); throw new Erro ...

Exploring the versatility of Angular Material classes beyond the boundaries of traditional Angular

We have embarked on the reconstruction of our web application and opted for Angular as our frontend framework, with Google Material as our primary style concept due to its simplicity and popularity. While most of our pages will be part of the Angular appl ...

Ways to verify a formarray in Angular?

Using editable with formarray and my model: class Book { id: number; name: string; active: boolean; } List of all books: [ {id: 1, name: 'book1', active: true}, {id: 2, name: 'book2', active: true}, {id: 3, name: 'book3 ...

Is Typescript capable of identifying void functions automatically?

Being new to Typescript and programming in general. Instead of using: function greet(greeting: string): void; Can I simplify it like this? Is there any type inference? function greet(greeting: string); ...

When deleting a row, the pagination feature in <mat-table> may encounter issues with the sticky

Struggling with a problem that I couldn't find a solution for online, so hoping to get some help here. I'm currently working on a dynamically-filled table where users can delete individual rows. The table has a sticky column and pagination, but I ...

Is there something I'm missing? The action buttons cannot be displayed on a preview of the event

Currently in the process of developing an angular application featuring a calendar component to showcase events, I opted to utilize angular-calendar for the visual representation. While exploring the month view functionality, I encountered an issue where t ...

Troubleshooting Angular: Resolving the Fatal Error 'SyntaxError: Unexpected token <' During Startup

I keep encountering this mysterious error repeatedly, especially after making changes to my Angular (2-5) dependencies. SyntaxError: Unexpected token < at eval (<anonymous>) at evaluate (http://localhost:5557/node_modules/systemjs/dist/sy ...

Prevent Duplicate Service Instances in Angular

After doing some thorough research online, I've identified the root of my issue: multiple instances of a particular service are being created. I need assistance in pinpointing and rectifying this problem within my code. The secondary service is depen ...

Tips for obtaining the OneSignal playerID

When launching the app, I need to store the playerID once the user accepts notifications. This functionality is located within the initializeApp function in the app.component.ts file. While I am able to retrieve the playerID (verified through console.log) ...