Issue: Attempting to assign a 'boolean' variable to a type of 'Observable<boolean>' is not compatible

I am currently working on the following code:

import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import {Observable} from 'rxjs';
import {AngularFireAuth} from '@angular/fire/auth';
import {map, tap} from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class ChatGuard implements CanActivate {

  constructor(private afAuth: AngularFireAuth,
              private router: Router) {
  }


  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable <boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {


    return this.afAuth.authState
      .pipe(
        map(user => user !== null),
        tap(value => {
          if (!value) {
            this.router.navigateByUrl('/login').then();
            return value;
          } else {
            return value;
          }
        })
      );
  }

}

Versions I am using are:

Angular CLI: 13.1.4

Node: 16.14.0

I encountered an error in this section of the code:

 return this.afAuth.authState
      .pipe(
        map(user => user !== null),
        tap(value => {
          if (!value) {
            this.router.navigateByUrl('/login').then();
            return value;
          } else {
            return value;
          }
        })

The error message says:

Type 'Observable<unknown>' is not assignable to type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'.Type 'Observable<unknown>' is not assignable to type 'Observable<boolean | UrlTree>'.Types of property 'source' are incompatible.

Do you have any suggestions on how to fix this issue?

Answer №1

The tap operator, as explained in the documentation, functions by running a specified Observer or callback for each item in an Observable.

This means there is no need to explicitly use return value within a tap operation, as it is automatically handled.

It is important to note that when dealing with redirecting routes based on boolean values, the redirection should be done before returning the value.

To improve your code, consider making the following changes:

    return this.afAuth.authState
              .pipe(
                map(user => { 
                   const isLogged = !!user;
                   if(!isLogged){
                      this.router.navigateByUrl('/login')
                      return false;
                   } else {
                      return true
                   }
                })
);

Additionally, it is possible for the this.afAuth.authState observable to emit a null value right before the user object upon page refresh (F5), leading to potential errors in authentication. To address this issue, I recommend incorporating a debounceTime operator before the map function.

Answer №2

The type 'Observable' does not match with the expected type of 'Observable<boolean | UrlTree>

Your method signature indicates a return type of Observable <boolean | UrlTree>, but you are returning an observable instead.

To fix this issue, you may need to adjust the signature of this.afAuth.authState to ensure it returns

Observable<boolean | UrlTree>

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

AmCharts issue in NextJS - Unusual SyntaxError: Unexpected token 'export' detected

Encountered an error while trying to utilize the '@amcharts/amcharts4/core' package and other amchart modules in a NextJS project: SyntaxError: Unexpected token 'export' After searching through various resources, I came across a helpf ...

Ignore one specific file when importing all files in Angular 7

In my Angular 7 project, I am utilizing C3 and importing all the necessary files at the beginning of my .ts component file using a wildcard. import * as c3 from 'c3'; While this method works well overall, I encountered an issue where my CSS ove ...

Adding a tooltip to an Angular Material stepper step is a great way to provide

I am trying to implement tooltips on hover for each step in a stepper component. However, I have encountered an issue where the matTooltip directive does not seem to work with the mat-step element. <mat-horizontal-stepper #stepper> <mat-step lab ...

Experimenting with a Collection of Items - Jest

I need to conduct a test on an array of objects. During the test coverage analysis of the displayed array, I found that the last object with the key link has certain conditions that are not covered. export const relatedServicesList: IRelatedServiceItem[ ...

How to Invoke a Function from Entry Component to Parent Component in Angular 7

My module includes the DragDropComponent in entry components, where the parent component consumes it like this: Parent Component: upload(data) { const modalRef = this.model.open(DragNDropComponent, { data: data, panelClass: 'defa ...

The React type '{ hasInputs: boolean; bg: string; }' cannot be assigned to the type 'IntrinsicAttributes & boolean'

I recently started learning react and encountered an error while passing a boolean value as a prop to a component. The complete error message is: Type '{ hasInputs: boolean; bg: string; }' is not assignable to type 'IntrinsicAttributes & ...

Utilizing precise data types for return values in React hooks with Typescript based on argument types

I developed a react hook that resembles the following structure: export const useForm = <T>(values: T) => { const [formData, setFormData] = useState<FormFieldData<T>>({}); useEffect(() => { const fields = {}; for (const ...

Navigating Tabs in Angular 4 with ngx-bootstrap and the Router

I am facing an issue with my tab navigation using the router. Only clicking directly on the link switches the tab and updates the route. However, if you click around or below the link, the tab switches but the route does not update. It seems like the issue ...

Issue with importing Typescript and Jquery - $ function not recognized

Currently, I am utilizing TypeScript along with jQuery in my project, however, I keep encountering the following error: Uncaught TypeError: $ is not a function Has anyone come across this issue before? The process involves compiling TypeScript to ES20 ...

Angular - Customizing button bindings for various functions

As a newcomer to Angular and TypeScript, I am faced with the task of creating a customizable button that can display text, an icon, or both. For example: button-icon-text-component.html <button> TEST BUTTON </button> app.component.html & ...

Using Angular, create mat-checkbox components that are dynamically generated and bound using

In my Offer class, I have a property called "units" which is an array of objects. export class Offer { public propertyA: string; public propertyB: string; public units: Unit[]; } export class Unit { public code: string, public name: ...

Displaying a collection of objects in HTML by iterating through an array

As someone new to coding, I am eager to tackle the following challenge: I have designed 3 distinct classes. The primary class is the Place class, followed by a restaurant class and an events class. Both the restaurant class and events class inherit core p ...

summing 3 numbers to a total of 100 percent

I am currently trying to calculate the percentages of different statuses based on 3 count values. Let's assume I have 3 statuses: 1) Passed 2) Failed 3) Skipped When dealing with only two cases, I was able to use a combination of the Floor and Ceil ...

I'm having trouble linking MikroORM migration to Postgresql - the npx command keeps failing. Can anyone offer some guidance on what

I am encountering a situation similar to the one described in this post. I'm following Ben Awad's YouTube tutorial: you can see where I am in the tutorial here. Objective: My goal is to execute npx mikro-orm migration:create in order to generate ...

Behavior of routing not functioning as anticipated

In my app-routing.module.ts file, I have defined the following routes variable: const routes: Routes = [ { path: '', redirectTo: '/users', pathMatch: 'full' }, { path: 'users', component: UsersComponent }, ...

Is there a way to automatically determine the parameters of a constructor to match the default class type in TypeScript

I need a function in a class that can utilize a type from constructor arguments, but I am unsure how to achieve this. class CustomClass<Type1, Type2=any>{ a: string = 'a' constructor(private readonly parameters: { attributes: Type ...

Is it possible to recycle an Observable within a function?

After reading numerous articles discussing Observables, Subscriptions, and different methods of unsubscribing, I found myself facing a simple question. The code snippet below is part of a function called getDataSource(): merge(this.sort.sortChange, this.pa ...

Angular - Unable to access property '$invalid' because it is null

Working on my login page with angular and typescript. Clicking the submit button should trigger the login function in the controller, but if the form is invalid, it should just return. New to typescript, I keep running into an error when trying to add an ...

A conditional type used with an array to return either an Error object or a generic type when the array is destructured

Within my Typescript project, I've implemented a Result type to be returned from functions, containing either an error or some data. This can take the form of [Error, null], or [null, Data]. Here's an example: type Result<Data> = [ Error | ...

Obtain user information post-payment with Angular's latest Paypal Checkout 2.0 feature

My app is all set up to sell various items, with PayPal handling the payment process. In order to generate invoices, I need to access user details such as their name and address, which are stored by PayPal for each user. How can I retrieve this information ...