What is the proper method for implementing a $http request in TypeScript that can be resolved in ui-router?

I have a straightforward HTTP service that I access through a service;

module shared {

    export interface IAuthService {
        isAuthenticated: () => any;
    }

    export class AuthService implements IAuthService {
        static $inject = ['$http'];

        constructor(private $http:ng.IHttpService) {
        }

        isAuthenticated():any {
            return this.$http({
                method: 'GET',
                url: 'http://localhost/auth'
            });
        }
    }

    export var app:ng.IModule = app || angular.module('shared', ['ngResource']);
    app.service('AuthService', AuthService);
}

And I utilize it in a route resolve;

$stateProvider.state('app', {
            url: "/app",
            abstract: true,
            templateUrl: "app/menu.html",
            controller: 'AppController',
            resolve: {
                authService: 'AuthService',
                isAuthenticated: function (authService) {
                    return authService.isAuthenticated();
                }
            }
        });

The issue is, I use HTTP response codes for the outcome -- if the user is authenticated, I send JSON data back (hence the any return type until I create the class). If not, I return HTTP/403.

This was working fine in JS, maybe by chance, but it appears that in transitioning to typescript, the 403 now completely halts the resolve process and the app just freezes.. Has anyone faced this before? Is there a better approach?

EDIT: I was requested for the generated JS code -- the .state remains the same, the service gets transformed into this;

AuthService.prototype.isAuthenticated = function () {
                return this.$http({
                    method: 'GET',
                    url: this.ConfigService.apiBaseUri + '/authentication/authenticated',
                    headers: { 'Authorization': this.ConfigService.sessionId }
                });
            };

Answer №1

Looking back, the answer seems quite obvious now. When a promise is rejected, it also rejects the state transition. Therefore, the best solution in cases where an $http call may fail but needs to proceed is to include a .then(function(data) {//...},function() {//...}) in the resolve method. In my scenario;

isAuthenticated: function (authService) {
    return authService.isAuthenticated().then(function(data) { return data; }, function() { return null; });
}

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

Deploy the Angular standalone component numerous times across a single page using Bootstrap

Edit After receiving input from Andrew, I have decided to adjust my strategy: Replacing survey-angular with the survey-angular-ui package Implementing a widget approach similar to the one outlined in this example Developing a single module that encompass ...

Error in ReactJS VSCode while integrating Cypress testing: The name 'cy' cannot be found

Currently working on a ReactJS Typescript project using NPM and VSCode. Despite all my Cypress tests running smoothly, I am encountering a syntax error in VSCode: Error: Cannot find name 'cy' Any ideas on how to resolve this issue? https://i.ss ...

Can someone help me troubleshoot why findMany is not functioning properly within my generic Prisma service? Additionally, what steps can I take

I'm currently tackling a project that involves creating a versatile service to display all entries from any Prisma model within my application. My approach utilizes TypeScript in conjunction with Prisma, aiming to dynamically pass a Prisma model to th ...

When the directive name conflicts with the attribute name

My issue arises from conflicting directive and attribute names. Here's the scenario: I have two directives, where the name of the first directive matches an attribute name of the second directive: angular.module('mymodule').directive(' ...

Nativescript encountered an issue: tns run android - "The compatible Android SDK could not be located"

After completing the entire Getting Started Tutorial for Mac (), I attempted to run the sample app. Although it worked fine on IOS, I encountered issues with Android - both on USB devices and Genymotion. Upon running "tns run android," I received the foll ...

Guide on restricting object keys to a specific set of strings in typescript

I am dealing with an API that has the ability to return one of these options: { fill: 'string'} or {stroke: 'string'} or {effect: 'string'} The key type I have established is as follows: type StyleKeyType = | 'fill&a ...

Issue: Module 'stylelint' not found in Angular Project

I've been attempting to execute this command to validate all of the .scss files (and even tried with .css files) and I keep encountering this error. $ stylelint "apps/**/*.scss" It worked once before but not anymore, even after restarting my compute ...

An error was encountered: Unable to assign value to the property "once" of [object Object] because it only has a

`Encountering an Uncaught TypeError: Cannot set property 'once' of [object Object] which has only a getter at HTMLDivElement.addEventListener (polyfills.js:1:146664). This issue is being faced during the process of upgrading the Angular version. ...

What's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

Maximize the performance of displaying images

At the moment, I have a set of 6 graphics (0,1,2,3,4,5)... The arrangement of these graphics looks fantastic! However, I am facing an issue when a user only has 3 graphics, for example 0, 2, and 5. In this scenario, my graphics do not line up correctly. D ...

WebStorm provides alerts for objects, types, and directives within Angular, yet they function properly

Why is WebStorm displaying warnings for objects, types, and directives in Angular Template HTML even though they are functioning correctly? Despite the fact that all types and Angular directives in the HTML structure are working fine within Angular on Web ...

Exploration of mapping in Angular using the HttpClient's post

After much consideration, I decided to update some outdated Angular Http code to use HttpClient. The app used to rely on Promise-based code, which has now been mostly removed. Here's a snippet of my old Promise function: public getUser(profileId: nu ...

What is the best way to include an entire public directory in Webpack to bundle all files?

I am considering switching from using gulp to webpack in my MEAN stack project. For the front end, I am utilizing AngularJs. This is a snippet from my webpack.config.js: const path = require('path'); module.exports = { mode: 'developmen ...

What is the process for interpreting the status code retrieved from an HTTP Post request?

When sending a POST request to a backend and attempting to read the status code, I encountered the following result: status-code:0 Below are my functions: Service: signIn(uname:string, pass:string): Observable<any> { let headers = new Headers( ...

Executing an HTTP POST request within an Angular 7 route guard: A step-by-step guide

In my Angular 7 application, I have implemented a route guard that is dependent on the response of a post call. The guard is structured like this: canActivate = (_router: ActivatedRouteSnapshot): boolean => { console.log('in link expiry guard& ...

Function calls are currently not enabled. Please consider substituting the function or lambda with a pointer to an exported function

Incorporating APP_INITIALIZER into my app has been a bit of a challenge. In the app.module.ts file, I have configured it with all the necessary imports like so: @NgModule({ ... providers: [ ..., ContextService, { provide: APP_INITIALIZER, useFactory: ...

Using CKEditor5 to Capture and Edit Key Presses

I'm currently working on capturing input from a CKEditor5 within an Angular application using TypeScript. While I am able to successfully display the CKEditor and confirm its presence through logging, I am facing difficulties in capturing the actual i ...

“What data type is typically received by functions through the `onClick` event?”

Recently, I've been working on some JavaScript code that resembles the following: const menu = ( <Menu onClick={handleMenuClick}> {menuItems.map((item) => ( <Menu.Item key={item.key} icon={item.icon} sty ...

Combining Angular with X3D to create a seamless integration, showcasing a minimalist representation of a box

I am brand new to web development, and I am feeling completely overwhelmed. Recently, I decided to follow the Angular tutorial by downloading the Angular Quickstart from this link: https://github.com/angular/quickstart. My goal was to add a simple x3d ele ...

Notification for background processing of $http requests

I am searching for a solution to encapsulate all my AJAX requests using $http with the capability to display a loading gif image during processing. I want this functionality to extend beyond just $http requests, to cover other background processing tasks a ...