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

Unable to add data to an Array once subscribed to BehaviorSubject

Hello everyone, this is my first time asking a question here. I hope it's clear enough for you to understand :) Let's dive straight into the issue at hand. I have a query regarding a behaviorSubject variable in TypeScript that is not allowing me ...

Enabling social media crawlers to function properly (such as Facebook and Twitter) in an Angular 11 Single Page Application (SPA

I've developed a Single Page Application (SPA) using Angular 11 and it's being hosted on a shared hosting server. The problem I'm facing is that I can't share any pages, except for the homepage (/), on social media platforms like Faceb ...

Is there a way to make PrismaClient return DateTime fields as Unix timestamps rather than JavaScript date objects?

When utilizing the PrismaClient for database interaction, DateTime fields are returned as JavaScript Date objects instead of Unix timestamp numbers. Despite being stored as Unix timestamp numbers in the database itself, I require the dates to be retrieved ...

What is the best way to iterate through an array within a class in Angular 2?

I am trying to iterate over an array named data, within another array containing 'champions'. Can anyone provide the correct syntax for this? I can successfully loop through all the champions within my IChampion interface, but I'm having tro ...

Issue encountered when attempting to deploy a node/express API with now.sh

Currently, I am in the process of deploying a node/express API with multiple endpoints on now.sh. I am seeking guidance on properly configuring the now.json file for this deployment. In order to provide a visual representation of my project's comple ...

I am facing an issue with my ngx-translator in Ionic4 as it is unable to retrieve the current language

I am having an issue with the ngx-translator package where I am unable to set the default language in my application. Here is the code snippet from my app.module.ts: import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import ...

Angular2: Issue encountered while processing click event

When I click a button on my client application, it sends a request to the server I created using Express. The request handler in the server simply logs 'Delete from server' every time the button is clicked. I am encountering these errors when cl ...

The attribute 'XXX' is not found within the type 'IntrinsicAttributes & RefAttributes<any>'

My coding hobby currently involves working on a React website using TypeScript. I recently came across a free Material UI template and decided to integrate it into my existing codebase. The only challenge is that the template was written in JavaScript, cau ...

Exploring Nested JSON Iteration in Angular4

I am struggling to iterate through a nested JSON and extract the desired output. Can someone assist me in retrieving the bpmn:startEvent id value from the JSON provided below? { "bpmn:definitions":{ "@attributes":{ "xmlns:xsi":"h ...

Combining various FormGroup types into a single object type in Angular 5

I am currently utilizing the mat-stepper feature from the Angular Material design library. Within my application, I am using 3 separate FormGroups to gather information and send it to a database using the httpClient method. To achieve this, I have defined ...

"String representation" compared to the method toString()

Currently, I am in the process of writing unit tests using jasmine. During this process, I encountered an issue with the following code snippet: let arg0: string = http.put.calls.argsFor(0) as string; if(arg0.search(...) This resulted in an error stating ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

The ESLINT_NO_DEV_ERRORS flag appears to be ineffective in my Typescript project

Currently, my project involves using the following tools: Yarn Typescript Create React App ESLint Make (Makefile) Fish shell During development, I encounter ESLint errors that prevent my project from compiling. To run my project, I use make run, which es ...

Is there a way to use Jest spyOn to monitor a function that is returned by another function?

I'm curious about why the final assertion (expect(msgSpy).toBeCalled()) in this code snippet is failing. What adjustments should be made to ensure it passes? it('spyOn test', () => { const newClient = () => { const getMsg = ...

Conceal components using routing in Angular2 release candidate 1

I have a request regarding certain elements that are to be displayed on all pages except the login page. I am considering using either ngIf or the hidden property of the elements to hide them when the user is on the login page. Here is what I have attempt ...

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

Setting up CI/CD for a project involving an API, Angular application, and database on Azure App Services

In my VSTS local GIT REPO, I have a solution file with three main projects: an API, an Angular App, and a SQL Server DB Project. There are also some test projects included in the solution. I am currently facing challenges in setting up CI/CD for this setu ...

Establishing a default value as undefined for a numeric data type in Typescript

I have a question regarding setting initial values and resetting number types in TypeScript. Initially, I had the following code snippet: interface FormPattern { id: string; name: string; email: string; age: number; } const AddUser = () => { ...