How to Resolve a Typescript Promise Syntax Error?

I have been working on creating a login authorization system to secure certain routes in an angular application, but I keep encountering a TypeScript error in the auth-guard.service during compilation. Despite my efforts, I am unable to pinpoint the issue. Below is the code for auth-guard.service:

 import { CanActivate,
        ActivatedRoute,
        RouterStateSnapshot,
        ActivatedRouteSnapshot,
        Router
    } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';

import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService, private router: Router ) {}

    canActivate(route: ActivatedRouteSnapshot,
                state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean  {
                    return this.authService.isAuthenticated()
                        .then(
                            (authenticated: boolean) => {
                                if (authenticated) {
                                    return true;
                                } else {
                                    this.router.navigate(['/']);
                                    return false;
                                }
                            }
                        );

    }
}

The error message I'm seeing reads as follows:

ERROR in src/app/auth-guard.service.ts(19,26): error TS2339: Property 'then' does not exist on type 'void'.

Here is the content of my auth-service.ts:

export class AuthService {
    loggedIn = false;

    isAuthenticated() {
        const promise = new Promise (
            (resolve, reject) =>  {
                setTimeout(() => {
                    resolve(this.loggedIn);
                }, 800);
            }
        );
    }

    login() {
        this.loggedIn = true;
    }

    logout() {
        this.loggedIn = false;
    }
}

Do I need to define a return value for isAuthenticated? What could be causing this issue?

Thank you in advance for any assistance...

Answer №1

It is essential to ensure that the promise is returned:

verifyUser() {
  return new Promise ((resolve, reject) =>  {
    setTimeout(() => {
      resolve(this.userVerified);
    }, 800);
  });
}

You also have the option of specifying its return type as follows:

verifyUser(): Promise<boolean> {
  ...
}

Answer №2

In order to properly handle authentication, the isAuthenticated method should always return a promise.

isAuthenticated() {
   const authPromise = new Promise (
      (resolve, reject) =>  {
         setTimeout(() => {
            resolve(this.userLoggedIn);
         }, 800);
      }
   );
   return authPromise;
}

Answer №3

To simplify the process, you can convert the method to async, which will automatically return a Promise without the need for using return new Promise()

async isAuthenticated() {
        new Promise (
            (resolve, reject) =>  {
                setTimeout(() => {
                    resolve(this.loggedIn);
                }, 800);
            }
        );
    }

Another approach is to create a wait helper function for better readability:

async isAuthenticated() {
        await wait(800);
       resolve(this.loggedIn);
    }

async wait(ms: number) {
  return new Promise((resolve) => {
      setTimeout(() => resolve(), ms);
   });
}

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

Troubleshooting error messages with Angular 2 HttpClient response payload

Currently, I am implementing the latest version (4.3) of HttpClient in angular to handle data POST requests to my backend server: this.httpClient.post<View>(`/path`, data).subscribe( (view: View) => console.log("Success"), (error: HttpErrorRe ...

The utilization of React.Component inheritance in TypeScript

In my attempt to develop a base class using React.Component and derive two classes from the base class, I have encountered an issue. Here is how I structured the classes: interface BaseItemProps { base_prop: string; } class BaseItem<P, T> exten ...

Initializing various objects on the same interface type array in one line

Is there a way to inline initialize an array of the interface type IFooFace in TypeScript with different specific implementations, similar to how it can be done in C#? Or do I have to initialize my objects before the array and then pass them in? In C#, th ...

Encountered issue with accessing the Error Object in the Error Handling Middleware

Below is the custom error validation code that I have developed : .custom(async (username) => { const user = await UserModel.findOne({ username }) if (user) throw new ConflictError('username already used& ...

Understanding how to pinpoint a particular request within an Angular 5 HTTP Interceptor

Currently utilizing the HTTPInterceptor feature in Angular 5 and things are running smoothly when it comes to cloning http-requests and sending them to the backend server. The issue arises with a particular GET request that polls the server for data every ...

Encountering Typescript issues while trying to access @angular/core packages

Recently, I made an update to my Ionic app from Angular 7 to Angular 8, and an odd error popped up: https://i.sstatic.net/icZOb.png The issue lies in the fact that I am unable to access any of the standard classes stored in the @angular/core module. This ...

Warning: Obsolescence of Typescript Detected

Having an issue with my login code in TypeScript. The 'subscribe' function is deprecated and I'm not sure how to proceed. Can anyone provide some guidance? doLogin() { this.userService.doLogin(this.loginForm.value).subscribe( r ...

The tsconfig.json file does not support the path specified as "@types"

Having set up multiple absolute paths for my Next.js application, I encounter an issue where importing a component from the absolute path results in something like "../componentName" instead of "@components/componentName" when I am inside another folder. T ...

Implementing undefined value acceptance in yup object when using Material-UI

Even though I have clearly specified that the key is optional in my Form, for some reason my input does not accept undefined as a value. Instead, I keep getting this error message: bonusPercentage must be a number type, but the final value was: NaN (cast ...

The shape-matching subset functionality in Typescript is experiencing issues

One of the key principles of TypeScript is that type checking focuses on the structure of values, a concept known as duck typing or structural typing. This means that only a subset of an object's fields needs to match for it to be considered compatibl ...

Component re-rendering and initializing useReducer

I made some revisions to this post. Initially, I shared the entire problem with my architecture and later updated it to focus directly on the issue at hand in order to make it easier for the community to provide assistance. You can now jump straight to the ...

Turn TypeScript - Modify type properties to reflect types of their descendants

I am currently working on creating a type that will modify a generic type based on its children. To provide some clarity, I have created a simplified example below: Original type type FormFields = { username: { type: string, ...

The art of combining Angular 6 with CSS styling for dynamic

Can we dynamically set a value in an scss file from the ts component like demonstrated below? public display: "none" | "block"; ngOnInit(): void { this.display = "none"; } ::ng-deep #clear { display: {{display}} !imp ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

Ways to adjust the ngx-pagination color scheme?

I am looking to customize the background color of ngx-pagination Here is my current code: <pagination-controls class="custom-pagination" id="indicadorPaginationResults" (pageChange)="p=$event" maxSize="9" directionLinks="true" autoHide="true" previ ...

Specific generic types do not incorporate abstract type context

Take a look at this code snippet: type Data = { person: { id: number; name: string; age: number } item: { id: number; name: string; price: number } transaction: { id: number; personId: number; itemId: number; quantity: number } } type Action<T ex ...

The error message "NextFunction does not have the property 'render'" appears when using Angular Universal in conjunction with Express

When attempting to implement server-side rendering for my Angular 6 app, I encountered the following error while using the Angular CLI universal demo as a reference: Property 'render' does not exist on type 'NextFunction'. This is the ...

Restrain a Key according to the data type of its value within a universal category

I am currently working on creating a versatile function where the generic type is used to define its parameter. Here's an excerpt from this parameter : type Configuration<T> = { masterdata: T[], target: ???? } I am encountering difficu ...

Making sure the checkbox stays selected in an angular environment

After experimenting with Angular 9 and a custom input, I achieved the following result => https://stackblitz.com/edit/angular-ivy-rgsatp My goal was to prevent users from disabling a radio button that is currently checked. Therefore, I made changes in ...