Creating an auth guard in Angular Fire v7 using the latest API (not backwards compatible)

I encountered an issue

Error: Unable to handle unknown Observable type

when attempting to utilize v7 Angular Fire with the latest API.
Specifically

"@angular/fire": "^7.4.1"
which corresponds to angular 14, firebase 9.
Please note, I have intentionally opted not to use compat imports anywhere in my application.

import { User } from '@angular/fire/auth';
import { AuthGuard, AuthPipe, AuthPipeGenerator } from '@angular/fire/auth-guard';

const redirectUnauthorizedAndUnverifiedToAuth: AuthPipe = map((user: User | null) => {
  // If user is not logged in, redirect to `auth`
  // If user is logged in and email is verified, allow redirect
  // If user is logged in but email is not verified, redirect to `auth/verify`
  return !!user ? (user.emailVerified ? true : ['auth', 'verify']) : ['auth']
})

const routes: Routes = [
  {
    path: "auth",
    loadChildren: () => import("./auth/auth.module").then(m => m.AuthModule)
  },
  {
    path: "my-feature",
    loadChildren: () => import("./my-feature/my-feature.module").then(m => m.MyFeatureModule),
    canActivate: [AuthGuard],
    data: { authGuardPipe: redirectUnauthorizedAndUnverifiedToAuth }
  },
  { path: "", redirectTo: "auth", pathMatch: "full" },
  { path: "**", redirectTo: "auth" }
];

Answer №1

Disclaimer: This information is current as of the time of writing https://github.com/angular/angularfire#developer-guide

AngularFire now offers a tree-shakable API, but it is still being actively developed with documentation in progress. As a result, developers are recommended to stick with the Compatibility API for now.

The new API requires an AuthPipeGenerator instead of AuthPipe despite the name authGuardPipe.

https://github.com/angular/angularfire/blame/master/src/auth-guard/auth-guard.ts#L21

const authPipeFactory = next.data.authGuardPipe as AuthPipeGenerator || (() => loggedIn);

Type definitions can be found at

import { AuthPipe, AuthPipeGenerator } from '@angular/fire/auth-guard';

Solution:

const authPipeGenerator: AuthPipeGenerator = () => redirectUnauthorizedAndUnverifiedToAuth

const routes: Routes = [
  ...
  {
    path: "my-feature",
    ...
    data: { authGuardPipe: authPipeGenerator }
  },

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

Expanding a given type using Typescript

My goal is to construct a custom table using Angular, where I aim to define a TableItem type that enforces the presence of a label property for every item added to the table. For instance, consider this example: <app-my-table [items]="items&qu ...

Creating a one-of-a-kind entry by adding a number in JavaScript

I am looking for a way to automatically add an incrementing number to filenames in my database if the filename already exists. For example, if I try to add a file with the name DOC and it is already present as DOC-1, then the new filename should be DOC-2. ...

What is the correct method for importing React in TypeScript (.tsx) to ensure optimal integration?

Within our TSX/React web application, we employ two distinct import styles for the react module: import * as React from "react"; as well as import React from "react" As far as I know, both methods function without any noticeable differences. Is there a ...

The 'sticky' nature of Firebase Authentication in Ionic

I have been working on integrating $firebaseAuth into my Ionic project. I followed a sample example from the Firebase website for logging in with Twitter (auth.$authWithOAuthPopup('twitter')) and incorporated it into my Ionic Framework. The code ...

Angular 2 error: "unknown element" issue persists despite exhausting all attempted solutions

Here's a typical scenario where I attempt to incorporate a component from another module : External component : import { Component, ViewEncapsulation, ElementRef, ViewChild, Input, Output, EventEmitter } from '@angular/core'; declare ...

Display or conceal an icon based on the data in the field

Can someone provide guidance on how to make an icon appear or disappear based on the logic within [ngIf]? The icon should only be displayed if there is information in a specific field. Should I implement this inside ngIF or in my TS file? Can the icon cl ...

Automatically reloading clients after deployment with Angular 10 for enhanced user experience

As of now, my application is live with all the JavaScript files having a timestamp version. However, when I rebuild my Angular app, the JavaScript files will be updated with a new timestamp version. https://i.stack.imgur.com/M8MDN.png Is there a method t ...

Angular 2 lacks compatibility with SVG

I have a website where I want to include SVG images inline with my HTML using Angular 2. However, when I try to load the SVG icons within a component, they do not display correctly. Instead, I see the following: https://i.sstatic.net/Ozo6E.png You can vi ...

When attempting to Dockerize an Angular CLI app, nothing seemed to happen

I attempted to dockerize my Angular application and created a Dockerfile as follows: FROM teracy/angular-cli as angular-built WORKDIR /usr/src/app COPY package.json package.json RUN npm install COPY . . RUN ng build FROM nginx:alpine LABEL author="pleijan ...

Setting up React Context API with TypeScript: A Step-by-Step Guide

I recently updated my app.js file to app.tsx for improved functionality. However, I encountered an error with the current value. app.tsx import React, { createContext, useState } from "react"; import SelectPage from "./pages/select/select& ...

Exploring the capabilities of UIGrid in conjunction with TypeScript DefinitelyTyped has been a

I've noticed that the latest release of UI Grid (RC3) has undergone significant architectural changes compared to nggrid. I am encountering some problems with the definitelytyped files for nggrid because they are from a different version. Will there ...

Creating a unique syntax for custom ngIf directives in Angular

Currently, I am in the process of developing a personalized *ngIf directive that will swap out content with a placeholder during loading. After referencing the *ngIf directive (https://github.com/angular/angular/blob/master/packages/common/src/directives/n ...

Validation of decimal numbers in JavaScript without the presence of any other characters

Looking to create a JavaScript regex to validate an 8-digit number that may include decimals. The current regex /^\d+$/ allows for any other characters such as ( , * $ etc. How can I modify this to only accept numbers and periods? For example, the nu ...

Including a hyperlink in a table using Angular 8

I have a table with multiple columns, one of which is the "documents" column that contains downloadable files. How can I make just the document name clickable as a link? HTML <p-table #dt3 [columns]="colsPermessi" [value]="permessi" [paginator]="true" ...

Conditional validation in Typescript based on the nullability of a field

I have come across the following code snippet: type DomainFieldDefinition<T> = { required?: boolean } type DomainDefinition<F, M> = { fields?: { [K in keyof F]: DomainFieldDefinition<F[K]> }, methods?: { [K in keyof M]: M[K] & ...

Utilizing the onscroll feature to trigger a function within a ScrollView

I am facing an issue with an animated view where I need to execute multiple events within the onScroll property. The current onScroll implementation is as follows: onScroll={ Animated.event( [{ nativeEvent: { conten ...

Maximizing the efficiency of enums in a React TypeScript application

In my React application, I have a boolean called 'isValid' set like this: const isValid = response.headers.get('Content-Type')?.includes('application/json'); To enhance it, I would like to introduce some enums: export enum Re ...

Tips for making concurrent API requests in Angular 7

Can anyone help me with sending multiple requests from different pages in Angular 7 and Typescript? For example, I have a page called Email where I need to send 1000 emails one by one and update the status in a variable. This process should run in the bac ...

Upgrade Angular from 12 to the latest version 13

I recently attempted to upgrade my Angular project from version 12 to 13 Following the recommendations provided in this link, which outlines the official Angular update process, I made sure to make all the necessary changes. List of dependencies for my p ...

The parameter type SetStateAction<MemberEntityVM[]> cannot be assigned the argument type Promise<MemberEntityVM[]> in this context

I am looking to display a filtered list of GitHub members based on their organization (e.g., Microsoft employees). Implementing React + TS for this purpose, I have defined an API Model which represents the structure of the JSON data from the GitHub API: ex ...