Allow a function to automatically stop after a specific duration

I'm in the process of developing a mobile application with the Ionic 2 framework, utilizing Angular 2.

One of the features I have implemented is a FileUpload option, which unfortunately experiences delays in cases of poor internet connections or app malfunctions. My goal is to set a timeout for this file upload after 7 seconds.

Is there a way to achieve this timeout within Angular 2?

My initial thought was to implement a workaround similar to the following (for demonstration purposes only, not actual code):

let doneUploading: boolean = false;
this.http.post(url, data, options).subscribe(response => {
   doneUploading = true;
   ....
}, err => {
   doneUploading = true;
   ....
});

setTimeout(()=> {
  if(!doneUploading) {
    alert("TIMEOUT");
  }
}, 7000);

Although this workaround gets the job done, it feels somewhat hacky. Is there a more streamlined solution within Angular 2, or should I stick with this workaround?

Answer №1

One useful feature in RxJS is the availability of .timeout() and .timeoutWith methods on Observable objects.

By using these methods, you can set a timeout for an HTTP post request like this:
let subscription = this.http.post(url, data, options)
    .timeout(7000, new Error("TIMEOUT"))
    .subscribe(response => {
    },
    err => {
       alert(err);
    });

For more information on how to use .timeout(), you can visit this link.

Answer №2

If your main concern is to prevent the callback from being executed after 7 seconds, you can achieve this by unsubscribing from your observable within that timeframe:

const subscription = this.http.post(url, data, options)
    .subscribe(response => {
    },
    err => {
    });
setTimeout(() => {
    subscription.unsubscribe();
}, 7000);

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

Sharing data between two components in an Angular2-Meteor application

I am currently working with angular2-meteor. When attempting to transfer a value between two components (updating the value in the first component triggers an event in the second component where the new value is used), I have two methods available: The ...

How to Retrieve Data Using an Authorization Token in Ionic 2 - Error Resolving Parameters for Headers

Hello, I am a newcomer to Ionic2 and would greatly appreciate any assistance. I am looking to retrieve data from a login API while also adding a token parameter in the header section. Below is my service code snippet: import { Injectable } from '@ang ...

Implementing centralized authentication through an IdentityServer application with the utilization of the resource owner password flow

I am currently developing two Angular 2 applications that will have a .NET Core 1.1 REST backend and be hosted on Azure App Service. My goal is to enable them to share authentication information in order to provide a seamless Single Sign-On experience. Add ...

How to convert JSON data (excluding headers) into a string array using TypeScript

I am attempting to extract the raw data from the JSON without including the headers. For example, I want to retrieve '1' but not 'ID', or 'foo' but not 'Name'. [{ID = 1, Name = "foo", Email = "<a href="/cdn-cgi/l ...

Different ways to modify the style of a MenuItem component in PrimeNG

Seeking advice on customizing the look of a MenuItem in PrimeNG. Here's what I have attempted so far: <p-menu [style]="{'width': '400px'}" #menuOpcoesLista popup="popup" [model]="opcoesListaCS" appendTo="body"></p-menu> ...

Trouble arises when applying CSS to ng-x accordion styling

While working with ng-x accordion in Angular 2, I successfully rendered my accordion component. However, I encountered an issue when trying to add styles to the template provided by ng-x accordion. Despite using CSS in my rendered component for classes l ...

Building a MEAN stack application using Angular 5 and implementing passportJS for authentication

What's the process for implementing authentication in a MEAN stack using Angular 5, Node.js, and Passport.js? ...

Steps to remove route parameter in Angular 5

In my Angular application, I have implemented a master detail view. When the user navigates to /blog/slug, it displays the selected post in the same component using the following code: ngOnInit() { this.route.params.subscribe((params) => { ...

Contrasting importing CSS directly in index.html versus using styleUrls in Angular 5

My landing page and dashboard components have different CSS styling, causing one of them to not function properly depending on the CSS. I tried removing these two lines from index.html: <link href="./assets/css/bootstrap.min.css" rel="stylesheet" /&g ...

issue with angular material mat-accordion on click event not scrolling to the top

When the expansion panel header in Angular Material is clicked, the onExpand function is supposed to be called. However, at that time, the window scroll should move to the top or change position but this functionality is not working as expected. onExpan ...

Examining the types of unions

Here is the scenario: interface CarData{ wheels: number } interface PlaneData{ wings: number } interface Vehicle{ type: string, data: CarData | PlaneData } function printWheels(data: CarData){ console.log("Number of wheels: " + data.whee ...

Navigating Through Angular 9 Values Stored Locally

I'm experiencing an issue with displaying a nested value from Localstorage in Angular. The problem seems to occur on the second *ngFor loop, whereas the first one works fine. However, when I try to run the second ngFor loop, I encounter an error stati ...

Utilizing async/await to pass a variable instead of subscribing to it

In my attempt to utilize the async/await method for a dual API call, I encountered an issue where variables within the second async function were not functioning properly or being rendered by Angular. const pokemon = this.httpClient .get(`https://pokeapi ...

Error in Nuxt/TypeScript: Unable to retrieve this - TS2339: Property 'XXX' is not found on type

I encountered an issue while working with Nuxt.js and TypeScript. In my project, I rely on dependencies such as axios or nuxt-i18n. As an example, let's focus on Axios. I followed the configuration outlined in the official documentation for nuxt/axios ...

Are there any alternative OpenAPI schemas that can produce more favorable Flow/TypeScript types, as the `oneOf` keyword is currently generating undesirable types?

We possess an OpenAPI schema that looks like this: { "openapi": "3.0.1", "paths": { "/v1/tool/breadcrumbs/{hierarchyId}/{categoryId}": { "get": { "tags": [ "V1-tool" ], ...

What is the best way to implement useAsync (from the react-async-hook library) using TypeScript?

Currently, I am utilizing react-async-hook to retrieve API data within a React component. const popularProducts = useAsync(fetchPopularProducts, []); The fetchPopularProducts() function is an asynchronous method used to make API calls using fetch: export ...

Is it possible to maintain the value of a variable even when localStorage is cleared?

In my Angular 14 application, I currently do not have ngrx state management implemented. I am facing an issue where I need to persist the value of a variable even if the user refreshes the page. There are two components involved in this scenario. In the fi ...

The error message "SPARTACUS is indicating that there is no 'unit' property defined for the 'Product' type

I need help adding a new attribute to the Product DTO in Spartacus. I followed the documentation and created a new TS file with the following code: declare module '@spartacus/core' { export interface Product { unit?: string; } } Howev ...

Steps to change image string information into a blob object

I'm currently faced with an issue wherein I need to download an image from the server and display it on the client side. Despite successfully downloading the image (confirmed in DevTools > Network > name-of-request > Preview), I'm encoun ...

Organize an array of objects into a custom tree structure with the data arranged in reverse

I have an array of objects structured as key value pairs with children forming a tree. For a clearer understanding, please see the attached screenshot. Despite trying various methods, I have been unable to achieve the desired result shown in the image. ...