What is the best way to execute an asynchronous request within a CanDeactivateFn guard in Angular?

Here's a strange question I've been grappling with lately.

So, I've got this function that essentially creates a custom Alert Window to handle unsaved form data when a user tries to navigate away. It may or may not be triggered depending on the situation.

export const unsavedDataGuard: CanDeactivateFn<boolean> = async () => {
    const utService: UTService = inject(utService);
    const alertService: AlertService = inject(AlertService);
    const unsaved = utService.unsaved;
    if (unsaved) {
        await alertService
            .openQuestion('Cancel?')
            .afterClosed()
            .subscribe(result => {
                if (result) {
                    return true;
                } else {
                    return false;
                }
            });
    } else {
        return true;
    }
};

The issue at hand is the error message I'm receiving:

Type '() => Promise<true | undefined>' is not assignable to type 'CanDeactivateFn<boolean>'.

Along with this warning:

Not all code paths return a value.

I get what the error is pointing to and where it stems from. If I simply return true or false after the await call, the error disappears. However, this deems the entire function ineffective as the alert will still pop up but won't serve any purpose since its buttons will become non-functional.

What perplexes me is why using the standard javascript confirmation window doesn't trigger an error:

confirm("Press a button!");

Since it should theoretically behave in a similar manner.

Answer №1

CanDeactivateFn allows for the acceptance of various return types such as Observable<boolean> or Promise. To implement this, simply avoid subscribing and return either an observable or a promise.

Here is an example:

return alertService.openQuestion('Cancel?').afterClosed()

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

Add TypeScript typings for npm utility manually by incorporating type definitions

I'm in the process of incorporating TypeScript into an existing JavaScript project, and I'm currently facing the challenge of adding typings to an npm module that lacks type definitions, which I anticipate will be a common issue. When I try to i ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...

Using Conditional Types in Supabase Query results in the TypeScript error, "Type is incompatible with type 'never'."

Query I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem. Helper Types Overview: Belo ...

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

The "path" parameter must be a string data type in order to proceed. The value received is currently undefined

My current project is utilizing Angular 8 When I attempt to run 'ng build --prod', my project encounters errors. ERROR in The "path" argument must be of type string. Received type undefined The issue arose after adding "enableIvy": true to the ...

Updating JavaScript files generated from TypeScript in IntelliJ; encountering issues with js not being refreshed

Struggling with a puzzling issue in IntelliJ related to the automatic deployment of changes while my server is running (specifically Spring Boot). I've made sure to enable the "Build project automatically" option in my IntelliJ settings. Whenever I ...

Sharing information between components in Angular through service communication

In my Angular 4 project, there is a functionality where upon clicking on one of the 'groups', its tile should be added to a list of 'favourites' which is represented as an array. To implement this feature, I utilized a BehaviorSubject. ...

Navigating in Angular 2: Ways to route to a different page while keeping the HTML hidden from the app.component.html file on the new page

Just recently, I encountered a minor issue. I already have a good understanding of how to navigate between different pages, but there's one thing that bothers me - each time I switch to a new page, the app.component.html always appears at the top of t ...

How to display a nested array in TypeScript following a specific structure

Can anyone assist with printing the variable below in the specified format? Data export const shop_items: Inventory:{ Toys{ Balls: { BallId: 001uy, BallName: Soccerball, SignedBy: David_Beckham, }, ...

Tips for utilizing various environment files for the "development" and "production" phases in the "aws-nodejs-typescript" template

I have utilized the "aws-nodejs-typescript" template from "serverless" to create a serverless function. My goal is to employ separate .env files for the "dev" and "prod" stages. Is there a way to accomplish this? Upon deployment, the correct stage is not ...

What causes the *ngIf to return true when compared to an observable that is either undefined or an empty object {}?

Why does this not result in false when the error$ object is undefined or an empty object represented as {}? Instead, it evaluates to true and shows the "Something went wrong" message. `<div *ngIf="(error$ | async) != null"> <span>Something w ...

Displaying Firebase data using Angularfire2 5.0 on an Ionic template

Hey everyone, I've been encountering a problem while trying to use angularfire2 v 5.0. I was comfortable using v 4.0 before, but now that I'm transitioning to v 5.0, I'm facing some issues. Does anyone know how I can display real-time data ...

What sets apart angular-cli from @angular/cli in the npm ecosystem?

Two angular cli packages can be found on npm: angular-cli currently at version 1.0.0-beta.28.3 @angular/cli currently at version 1.0.0-beta.31 What sets these two packages apart, and which one is recommended for a new project? The information provided ...

Show refined information upon form submission or click

I am facing a challenge with implementing filtering functionality in an input box within a form in Angular 12. Despite my efforts, I have been unable to get the pipe working correctly in the component and consequently in the view. HTML ...

The 'changes' parameter is inherently defined with an 'any' type.ts(7006)

Encountering an error and seeking help for resolution. Any assistance would be highly appreciated. Thank you. Receiving this TypeError in my code. How can I fix this issue? Your guidance is much appreciated. https://i.sstatic.net/cWJf4.png ...

Exploring the world of ng2-translate for translating texts

For the translation of headings and texts in my Angular2 web application, I utilized ng2-translate. However, I am facing a dilemma when it comes to translating texts that are passed from a .ts file. For example, I can easily translate texts in an HTML fi ...

Concealing Bootstrap Dialog in Angular 6 through Component隐藏Angular 6中

I have been struggling to hide a bootstrap dialog from a component with no success. Here is my Dialog code: <div class="modal fade" id="loading_video_upload" tabindex="-1" role="dialog" aria-labelledby="loading_video_upload_label" aria-hidde ...

The saved editable input number is automatically pushed even without needing to click on save or cancel

I am working with a datatable, chart, and a label that shows the latest added value. The table and chart display time-series data for the last 30 minutes, including the timestamp and a random numerical value between 0 and 999. Every 10 seconds, a new data ...

What is the reason behind the error Generic indexed type in Typescript?

Here is a scenario where I have a specific generic type: type MapToFunctions<T> = { [K in keyof T]?: (x: T[K]) => void; }; It functions correctly in this instance: type T1 = { a: string }; const fnmap1: MapToFunctions<T1> = { a: (x: st ...

Deploying AWS CDK in a CodePipeline and CodeBuild workflow

I am currently attempting to deploy an AWS CDK application on AWS CodePipeline using CodeBuild actions. While the build and deploy processes run smoothly locally (as expected), encountering an issue when running on CodeBuild where the cdk command fails w ...