Unlock the potential of Angular $http by leveraging TypeScript generics in your web development projects

I have been attempting to implement a generic promise return in my code:

public getUserData: () => ng.IPromise <string> = () => {
        var promise = this.makeRequest<string>('http://someurl.com',null)
            .then((response:string) => {
                    let responseData: string = response;
                    return responseData;
                }
            )
            .catch((error) => {
            });

        return promise;
    };

        public makeRequest<T>(url: string, data?: any,
                          config?: any, verb?: HttpMethod): ng.IPromise<T> {
        // Cache key holds both request URL and data
        var cacheKey = url + '*' + JSON.stringify(data);

        var deferred = this.$q.defer();
        var httpRequest: any;
        var responseData: T;
        var startTime = new Date().getTime();

        // Attempting to retrieve cached data if necessary
        if (!config || config.cache != false) {
            responseData = this.cacheService.get(cacheKey);
        }

        if (responseData) {
            deferred.resolve(responseData);
        }
        else {
            switch (verb) {
                case HttpMethod.GET:
                    httpRequest = this.$http.get(url, config);
                    break;
                case HttpMethod.POST:
                    httpRequest = this.$http.post(url, data, config);
                    break;
                case HttpMethod.PATCH:
                    httpRequest = this.$http.patch(url, data, config);
                    break;
                default:
                    httpRequest = this.$http.post(url, data, config);
                    break;

            }

            httpRequest
                .then((res: any) => {
                    responseData = res.data;
                    this.cacheService.put(cacheKey, responseData);
                    deferred.resolve(responseData);
                })
                .catch((error: any) => {
                    deferred.reject(error);
                });
        }

        return deferred.promise;
    }

However, I am encountering the following error message when calling getUserPreferences:

Error:(132, 9) TS2322: Type '() => IPromise' is not assignable to type '() => IPromise'. Type 'IPromise' is not assignable to type 'IPromise'. Type 'void' is not assignable to type 'string'.

Answer №1

Seems like the issue arises from not resolving the promise with responseData. Omitting resolve(responseData) resulted in the promise resolving implicitly with undefined.

Give this a shot:

public sendRequest<T>(url:string, data?: any): ng.IPromise<T> {
    return this.$http.post(url, data)
           .then((res: any) => {
               return res.data;
           });
}

I also got rid of the unnecessary deferred object since you can directly return the promise.

One more thing, I excluded the catch block because it's preferable to place it at the end of the promise chain (within getUserPreferences).

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

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

How to effectively handle JWT client_id on a Javascript backend using ASP.NET Web API

I am currently in the process of implementing JWT authorization within a project. However, I have encountered an issue where I need to pass the client_id from my AngularJS frontend to the ASP.NET Web API backend in order to successfully obtain the token. T ...

How can I limit the radius of a circle in Angular Google Maps?

I am utilizing angular-google-maps and attempting to limit a circle's radius. For example, when the radius_changed event is triggered, I check the radius value and if it's less than 100, I set it to 100. Unfortunately, this approach doesn't ...

Once all the asynchronous $http calls have finished loading, bring up the Template/Controller route

At this time, my index.html file contains the following: <div ng-controller="MainCntl"> <div ng-view></div> </div> The ng-view directive is responsible for loading either "template1.html" or "template2.html" based on the rou ...

Error in React Typescript hook: The function is not executable

Since transitioning the code from React JavaScript to React TypeScript, I have been encountering an issue. I had a simple hook that toggles state between on/off or true/false. I am struggling with this transition as the code used to work perfectly in Java ...

A script object must only permit one property at a time

I am unfamiliar with TypeScript and I have an object named obj with 3 properties: a, b, c. However, it is important to note that b and c cannot exist together in the same object. So, my object will either be: obj = { a: 'xxx', b: 'x ...

Enabling cookie communication between NestJS server and Next.js frontend

I seem to be encountering challenges when trying to set cookies from a NestJS backend into my Next.js app. My NestJS application is running on port 3001 and here is my bootstrap setup: async function bootstrap() { const app = await NestFactory.create(Ap ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

Guide on invoking personalized server-side functions (such as object parsing) utilizing Typescript and Angular tools

I've been grappling for weeks to make custom service calls function with Typescript / Angular / C#. It's been a challenge to find a workable solution online, and the more I search, the more bewildered I become. My current approach has largely be ...

To properly format the date value from the ngModel in Angular before sending it to the payload, I require the date to be in the format

When working with Angular 9, I am facing an issue where I need to format and send my date in a specific way within the payload. Currently, the code is sending the date in this format: otgStartDate: 2021-07-20T09:56:39.000Z, but I actually want it to be for ...

Internationalization in Angular (i18n) and the powerful *ngFor directive

Within my Angular application, I have a basic component that takes a list of strings and generates a radio group based on these strings: @Component({ selector: 'radio-group', templateUrl: `<div *ngFor="let item of items"> ...

Monitor when users enter commas into input fields in AngularJS

My current challenge involves monitoring user input in a text field and validating the input when a comma is typed, instead of using ng-click="action()". I am looking to implement something like Comma-Typed="action()", but my attempts with ng-change and sc ...

Error message: "The toJSON method is not found for the item in the nested array of

Encountering an issue with NSwag in my Angular project where it throws an error when attempting to send data if the object contains a nested array of objects like this: export interface IJobAdDto { mainJobAd: JobAddDetailsDto; differentLanguageJobA ...

Encountered an EACCESS error while attempting to generate package.json in Angular

Upon completing the command line "yo angular" and following all the necessary steps, I encountered this error : Screenshot of the error I attempted to run it using "sudo yo angular" but unfortunately, it did not resolve the problem. Does anyone have any ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

Contact a relaxation service periodically to pause its operation

To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received: function m ...

AngularJS helps with formatting dates in a more organized manner

I'm looking for a directive in Angular that will allow the user to enter a date in the format 2/3/67 into an input field and have it automatically formatted as 02/03/1967. I've tried a few approaches on my own but haven't been successful. ...

Utilize jQuery to load AngularJS libraries into your web application

Trying to incorporate AngularJS into a jQuery-built webpage has been my latest challenge. While the rest of the site was developed using jQuery, I wanted to tap into the potential of AngularJS for a specific page. That's when I decided to do this: jQ ...

Difficulty with two-dimensional arrays in Angular and Typescript

I am currently stuck trying to assign values to a 2-dimensional object array in Angular/Typescript. I have noticed that the last assignment seems to override the previous ones, but I cannot pinpoint why this is happening. Could someone please review my cod ...

The Nest.js Inject decorator is not compatible with property-based injection

I am facing an issue with injecting a dependency into an exception filter. Here is the dependency in question: @Injectable() export class CustomService { constructor() {} async performAction() { console.log('Custom service action executed ...