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

Seeking assistance with TypeScript promises

Just starting out with typescript and nodejs, but I've got to tackle some issues in the typescript code. I'm looking to execute an ECS one-off task using Pulumi. I have the documentation on how to run the task from the taskDefinition, which can ...

How can you verify the correctness of imports in Typescript?

Is there a way to ensure the validity and usage of all imports during the build or linting phase in a Typescript based project? validity (checking for paths that lead to non-existent files) usage (detecting any unused imports) We recently encountered an ...

Error: Import statement cannot be used outside a module (@cucumber/cucumber) while using Node.JS, Playwright, and Cucumber framework

I encountered an issue while attempting to compile my Node.js code that is compliant with ECMAScript 6: $ npx cucumber-js --require features/step_definitions/steps.ts --exit import { Before, Given, When, Then } from "@cucumber/cucumber"; ^^^^^^ ...

Is there a way to modify CSS class names on-the-fly within an Angular project?

I am working with two CSS classes named as below: .icon_heart{ color: #bdbdbd; } .icon_heart_red{ color: #a6b7d4;; } Within my HTML code, I have incorporated a heart icon. <div class="icon_heart" *ngIf="showheartIcon"> ...

When I try to pass a formControl to a child component in Angular, it throws a "no value

What could be causing the error message "no value accessor for form control with unspecified name" to appear? I am working with the edit-component: Here is the code in HTML: <mat-form-field> <input [formControl]="formControl"> </mat-f ...

Creating a custom Angular Material Stepper form with modular steps implemented as individual components

Angular Material stepper is functioning well in a single component, but now I need to use it in around 10 different components, each with different types of forms. To address this, I have decided to break down the stepper into separate components, with eac ...

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

Using Angular2 cli along with material design, the error message "The argument `$map` in the function `map-get($map, $key)` must

After updating my environment with newer versions of @angular/cli and @angular/material, I am facing difficulties in getting my angular2 application to run. ERROR in ./src/app/components/general/table/table.scss Module build failed: undefined ^ ...

Exploring Angular 2's Elementary Observation and Subscription Technique

I am currently attempting to retrieve data from a JSON encoded PHP script API utilizing the following code: export class AppComponent { test = 'Angular is live'; private data; constructor(private http:Http) {} ngOnInit() { ...

Printing reports in Angular 9

I have a requirement in my Angular 9 application to generate and print reports. 1. I am looking for suggestions on how to handle printing reports where a user triggers the action by clicking a button, and the report data needs to be fetched from the datab ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

How to include a sub-route in Angular after adding parameters?

In this scenario: 'www.xyz.com/#/indutry/1/subIndustry/2/subSubIndustry/3' I am looking to implement this structure in my Parent route file. How can I achieve this using ForRoot? ...

What is the process for transforming an exported function into a function type?

When writing Express middleware, I am facing challenges in deciding how to properly typecast my functions. For instance, when working on an error handler: export function errorHandler(err, req, res, next) { ... } TypeScript correctly points out that th ...

How can I transfer the document id from Angular Firestore to a different component?

I'm seeking assistance on how to achieve a specific task related to pulling data from Firestore in my Angular application and displaying it in a list. Everything is working smoothly, including retrieving the document ID. My goal is to have the retrie ...

What is the best way to specify Next.js Context types in TypeScript?

Can someone help me with defining the types for next js Context and req? Below is the code for the getServerSideProps function- //Server side functions export const getServerSideProps: GetServerSideProps = async (context) => { await getMovies(conte ...

Tips for creating React/MobX components that can be reused

After seeing tightly coupled examples of integrating React components with MobX stores, I am seeking a more reusable approach. Understanding the "right" way to achieve this would be greatly appreciated. To illustrate my goal and the challenge I'm fac ...

Is there a way to make sure video files are downloaded instead of automatically playing in the browser window?

I have a link to a video file with various formats like mp4, 3gp, etc. When I click on the link, it opens in the same tab. Changing the target attribute to "_blank" makes the video open in a new tab. However, when I ctrl-click the link, the file s ...

Array updating using the foreach method in Angular

Hey everyone, I've encountered an error that seems to be related to scope and I could use some advice. I'm currently looping through an array and trying to push the results to another array. However, when I attempt to push the results to public m ...

Can a button be incorporated into an accordion feature using DevExtreme Angular?

I am using devextreme-angular and I would like to include two buttons such as DELETE and EDIT to accordion. The accordions receive the posts I typed so i have title and content for each accordion. What I need now is to add these buttons to each of the cont ...

Is there a way to display the data from a URL as selectable options in a dropdown menu?

I have a URL containing an arrayList of data. My task is to fetch the data from this URL and display it as options in a dropdown menu, allowing users to select the desired option. I am aware that this can be achieved using the Get method, but I am facing d ...