Developing an Angular service to incorporate retry functionality for $http.get requests in Typescript

Looking to add offline support to my angular web-app, but struggling to get my simple retry function to function properly. My service code is as follows:

constructor($http: ng.IHttpService, private $q: ng.IQService, private $interval: ng.IIntervalService, private $timeout: ng.ITimeoutService) {           
        this.httpService = $http;
    }
getCategories(updatedFunction: Function) {
        var deferred = this.$q.defer();

            this.httpService.get('/api/listCategories')
                .success((response) => {
                deferred.resolve(response);

            }).error(() => {
                this.$timeout(() => this.getCategories(), 10000);
            });
        return deferred.promise;
    }

On the controller side, I have the following:

    service.getCategories().then(c => {
                //Code here
            });

When online, the service works fine and I receive the expected data. However, if I am offline at the start, I start receiving "GET http://correct_looking_path/ ERR_FAILED" and when I debug the JS file, I see that the httpService.get method runs but instantly fails to .error(). Even after connecting, I still receive the same error message and pattern. The httpService.get method runs every 10 seconds but fails consistently.

Refreshing the page seems to solve the issue.

Answer №1

The main issue arises from the disconnect between your .error() callback and the deferred object in your code. Consider implementing an optional TypeScript parameter to pass the deferred object, allowing you to chain the recursive calls effectively.

fetchCategories(updatedFunction: Function, errorDeferral?: angular.IDeferred<{}>) {
    var deferred;
    if (errorDeferral) {
        deferred = errorDeferral;
    } else {
        deferred = this.$q.defer();
    }

    this.httpService.get('/api/listCategories')
        .success((response) => {
        deferred.resolve(response);

    }).error(() => {
        this.$timeout(() => this.fetchCategories(deferred), 10000);
    });
    return deferred.promise;
}

Answer №2

The issue I encountered was due to my failure to include my API request (/api/listCategories) in the NETWORK section of my .appcache file. As a result, the application attempted to retrieve a cached resource that was non-existent instead of initiating a legitimate HTTP request.

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

Obtain the data from onTouchTap action

Currently, I have a class that is returning an event to the parent. My goal is to extract the number of the touched button (the label on RaisedButton). Although I am successfully returning the event, I am unable to locate the desired information when I l ...

My React JS page suddenly turned blank right after I implemented a setState() function within my functional component

I was working on my code and everything seemed fine until I tried to incorporate the setState function with setcategory and setvalue. However, after making this change, my react page suddenly went blank. Can anyone help me identify what went wrong and pr ...

Is a UI routing race problem a concern?

After some observation, I've identified a potential race condition that occurs when switching between states too quickly. For example, let's say I navigate to state A. The directives linked to this state are compiled. This process could take lon ...

Passing an array of objects as properties in React components

My functional component looks like this: function ItemList({ items }: ItemProps[]) { return <p>items[0].name</p> } Here is how I'm creating it: <ItemList items={items} /> The array items contains objects in the format [{name: &ap ...

No content returned by Angular Server

I have implemented a factory in angular 1.6 to make GET requests to a Rails 5 server. The factory contains an $http call like this: $http({method: 'GET', url: urlString, params: dataToSend}) .then(function successCallback(response) { ...

How to delay setting a property in Angular 2 until the previous setter has finished execution

Hey there, I'm facing an issue with my component. Within my component, I have an input setter set up like this: @Input() set editStatus(status: boolean) { this.savedEditStatus = status; if (this.savedEditStatus === true && this.getTrigg === t ...

When a function is included in an object, it transforms into something other than a function

In my model, it looks like this: export default class UserObject { name: string; id: string; validateInsert() { } } If I interact with the model in this way: const modelUser: UserModel = new UserModel(); modelUser.ID = 1; modelUser ...

What is the best way to have child controllers load sequentially within ng-repeat?

Currently, I have a main controller that retrieves data containing x and y coordinates of a table (rows and columns). Each cell has a child controller responsible for preparing the values it will display based on the x and y values from the parent control ...

The client.postMessage() function in a service worker is not being recognized by the onmessage handler within an AngularJS controller

Handling Service Worker Messages: let angularClient; self.addEventListener('message', function(event) { // store the client that sent the message in the angularClient variable angularClient = event.ports[0]; }); Service Worker Notificat ...

Troubleshooting problems with displaying views due to asynchronous $http.get calls in AngularJS

Within my application, I am utilizing two separate API calls. The initial call retrieves a catalog of services along with their unique ID's. Subsequently, once the ID information is acquired, a second call is made to retrieve pricing data for each cor ...

What is the process for ensuring that the "ng-multiselect-dropdown" is a mandatory field within Angular 7?

Is there a way to require the ng-multiselect-dropdown field to have at least one selected item? <ng-multiselect-dropdown [placeholder]="'Select countries'" [data]="countries" [(ngModel)]="countriesSelectedItems" [settings]="co ...

Upon calling set() on Map, the object returned does not conform to a Map data structure

I've been exploring the transition to using immutable.js for managing states: class Register extends Component<{}, Map<string, string>> { state = Map<string, string>(); onInputValueChange(e) { const { name, value } ...

What is the best way to create a unit test for a controller that utilizes $state?

Currently working on creating a unit test for my controller: app.controller('StartGameCtrl', function ($scope, $timeout,$state) { $scope.startGame = function () { $scope.snap = false; $scope.dealCards(); debugger; ...

Creating a constant in an AngularJS module: The definitive guide to defining module-specific constants

Within a page, numerous Angular modules are present. I have set up a constant for each module containing the version number. var module1 = angular.module('module1').constant('version', '1.2.3'); var module2 = angular.module(& ...

Guide on how to load a document and transfer information to a webpage using a single GET request

I am currently utilizing AngularJS on the client-side and Express.js on the server-side. My goal is to render a page and transmit data to populate a table in a single get request. I attempted using the EJS engine to populate the table on the server-side b ...

Guide to incorporating ThreeJS Collada loader with TypeScript / Angular CLI

I currently have three plugins installed: node_modules/three My Collada loader was also successfully installed in: node_modules/three-collada-loader It seems that the typings already include definitions for the Collada loader as well: node_modules/@ty ...

How can we enhance intellisense to recognize instance members of an interface when using dynamic indices?

In the midst of developing an angular project, I am currently utilizing an interface to specify a configuration for a module. The design of the interface revolves around mapping names to objects and is relatively straightforward: export interface NamedRou ...

Guide to fetching a string using Angular's http client?

I am facing an issue with calling a server that returns a csv file as text. I am using Angular's HttpClient and I need to prevent it from trying to cast the csv file to JSON. I tried setting the responseType to 'text' in the httpOptions, but ...

Typescript: When using ts-node-dev, an error occurred while trying to import express due to an unexpected

I am embarking on a fresh project using Typescript and I intend to set up the node server with typescript utilizing express. There's a helpful tutorial that explains how to execute a Typescript file without going through the hassle of compiling files, ...

What is the best way to trigger an AngularJS function after a row selection event in Django?

In order to display the selected row id when a row selection event takes place in the datatable worklist, I am attempting to achieve this using an AngularJS function shown below: function showSelectedRowId($scope){ var dtWorklist = datatable_work ...