The input of type 'Observable<true | Promise<boolean>>' cannot be assigned to the output of type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'

I'm currently using a Guard with a canActivate method:

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      return this.fireAuth.authState.pipe(
        take(1),
        map(authState => !!authState),
        map(auth => !auth ? this.router.navigate(['/']) : true)
      )
  }

The functionality works fine, but I am encountering a typescript error in the console:

ERROR in auth.guard.ts(20,7): error TS2322: Type 'Observable>' is not assignable to type 'boolean | UrlTree | Observable | Promise'.

Can anyone suggest a solution for resolving this error?

Answer №1

Avoid using the map() function in this scenario. The goal is not to alter the emitted value, but rather to generate a side effect.

take(1),
map(authState => !!authState),
tap(auth => {
  if (!auth) {
    this.router.navigate(['/']);
  }
});

Alternatively, for better clarity:

take(1),
map(authState => {
  if (authState) {
    return true;
  } else {
    this.router.navigate(['/']);
    return false;
  }
});

Another option is to have the map function return a UrlTree for navigation purposes:

take(1),
map(authState => !!authState || this.router.parseUrl('/'))

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

Adjust the font size in Chart.js for improved resolution across all types of monitors (i.e. creating charts that are not specific

Everything is looking great on my chart with the labels perfectly displayed at the defined font size. However, I am facing an issue when viewing the chart in higher resolutions as the font sizes appear small. Is there a way to dynamically adjust all size-r ...

Tips for resolving the issue with the 'search input field in the header' across all pages in angular 5 with typescript

I currently have a search field in the header that retrieves a list of records when you type a search term and click on one of them. The search function utilizes debounceTime to reduce API requests, but I'm encountering an issue where the search doesn ...

Leverage the nativeElement property within two separate components

Encountering an error in the autocomplete feature for Angular Maps (AGM), which reads: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined TypeError: Cannot read property 'nativeElement' of ...

Using the `disableSince` option in `mydatepicker` for validating date of birth

Currently, I am utilizing the mydatepicker plugin for my calendar field, specifically for the Date of Birth field. It is important for me to disable future dates by setting the current date as a reference point. While exploring the documentation, I came ...

Utilizing Google Closure Library with Angular 6

I am looking to integrate the google closure library into my angular 6 application. To achieve this, I have utilized the following commands: npm install google-closure-compiler and npm install google-closure-library. My application can be successfully co ...

Utilizing Express, Request, and Node.js to manage GET requests in typescript

I'm struggling with using Express and Request in my project. Despite my efforts, the response body always returns as "undefined" when I try to get JSON data from the server. In my server.js file, this is the code snippet I have been working on: impo ...

Angular Owl Carousel doesn't slide horizontally, it slides vertically

Within my Angular project, I incorporated an Owl Carousel into the home-component.html file. Here is a snippet of the code: <section> <div class="container"> <h1 class="products-title">New Arrivals</h1> ...

Issues have been reported with Angular 10's router and anchorScrolling feature when used within a div that is positioned absolutely and has overflow set

I feel like I may be doing something incorrectly, but I can't quite pinpoint the issue. Any help or pointers would be greatly appreciated. My current setup involves Angular 10 and I have activated anchorScrolling in the app-routing.module file. const ...

Angular API for search filtering input

I am currently retrieving data from an API in my service. I now need to implement a search filter by name. Here is the code for the Service: export class ListService { listUrl = 'https://swapi.co/api/planets'; constructor(private ht ...

In search of assistance with resolving a React Typescript coding issue

I need help converting a non-TypeScript React component to use TypeScript. When attempting this conversion, I encountered the following error: Class 'Component' defines instance member function 'componentWillMount', but ext ...

What steps do I need to take in order to ensure that each webpage displays unique thumbnails?

As a newcomer to website development, I recently looked into implementing open graph on my site. However, I ran into an issue where I could only set one thumbnail for the entire website. This posed a problem as I wanted each navigation menu tab (Home, Abou ...

Polling with RxJs, handling errors, and resetting retryCount with retryWhen

I am currently working on setting up a polling strategy that functions as follows: Retrieve data from the server every X seconds If the request fails, show an error message: "Error receiving data, retry attempt N°"... And retry every X seconds for a maxi ...

Troubleshooting Node.js and Angular: Resolving the "Cannot Get"

I've successfully retrieved data from Angular and can store it in my local database without any issues. However, when I check the backend server in the web browser, I'm seeing the error message below: Cannot GET Even though the server is rece ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

What could be causing the conditional div to malfunction in Angular?

There are three conditional div elements on a page, each meant to be displayed based on specific conditions. <div *ngIf="isAvailable=='true'"> <form> <div class="form-group"> <label for ...

The fixed header option is not available for the CdkVirtualScrollViewport

Looking for a solution in my Angular application where I need to keep the table header at a fixed position while displaying the scrollbar only on the body part. Currently, I am utilizing the CdkVirtualScrollViewport library in Angular to render the table c ...

Angular2, multi-functional overlay element that can be integrated with all components throughout the application

These are the two components I have: overlay @Component({ selector: 'overlay', template: '<div class="check"><ng-content></ng-content></div>' }) export class Overlay { save(params) { //bunch ...

Allow web applications in Apache ServiceMix to communicate across different domains by enabling Cross

My current project involves deploying an angular2 webapp in servicemix as a war file. As a result, the app runs on the localhost:8181/angular2webapp URL. Additionally, I have a bundle installed for handling REST requests, which essentially functions as a c ...

What could be the reason it's not functioning as expected? Maybe something to do with T extending a Record with symbols mapped

type Check<S extends Record<unique, unknown>> = S; type Output = Check<{ b: number; }>; By defining S extends Record<unique, unknown>, the Check function only accepts objects with unique keys. So why does Check<{b:number}> ...

Guide to aligning a fraction in the center of a percentage on a Materal Design progress bar

Greetings! My objective is to create a material progress bar with the fraction displayed at the top of the percentage. Currently, I have managed to show the fraction at the beginning of the percentage. Below is the code snippet: <div class=" ...