Implementing User Role-based Access Control in Firebase - Troubleshooting Error with switchMap

I am currently working on implementing Role-Based User Access Control With Firebase in order to grant access to a route only if the user is authenticated and has admin privileges. I am following this tutorial for guidance:

My AuthService

import { Injectable } from '@angular/core';
import {AngularFireAuth} from 'angularfire2/auth';
import {Observable} from 'rxjs/Observable';
import {User} from '../models/user.model';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {AngularFireDatabase} from 'angularfire2/database';
import * as firebase from 'firebase/app';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class AuthService {
  user: BehaviorSubject<User> = new BehaviorSubject(null)

  constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
    this.afAuth.authState
      .switchMap(auth => {
        if (auth) {
          /// signed in
          return this.db.object('users/' + auth.uid)
        } else {
          /// not signed in
          return Observable.of(null)
        }
      })
      .subscribe(user => {
        this.user.next(user)
      })
  }

}

My User Model

export interface Roles {
  reader:boolean;
  admin?:boolean;
}

export class User {
  id:number;
  admin:boolean;
  activated:boolean;
  usertype:string;
  profile : {
    title:string;
    firstname:string;
    lastname:string;
    gender:string;
    houseNr:string;
    plz:string;
    street:string;
    place:string;
    nation:string;
    email:string;
    companyname:string;
    ustID:string;
    phone:number;
    mobile:number;
    fax:number;
    intPhonePrefix:string;
    intMobilePrefix:string;
    intFaxPrefix:string;
    phonePrefix:string;
    mobilePrefix:string;
    faxPrefix:string;
    bankDepositor:string;
    bankIban:string;
    bankBic:string;
    bankInstitute:string;
  }
  roles: Roles;

  constructor() {
    this.roles = { reader: true }
  }
}

Unfortunately, I encountered a syntax error on .switchMap(auth => {:

https://i.sstatic.net/b0c68.png

Any idea what could be causing this error?

Answer №1

One important task is to utilize a pipe when working with data processing.

this.afAuth.authState.pipe(
      switchMap(result => .... ))

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

Exploring the capabilities of Laravel for accessing Firestore queries

Currently, my Laravel application is working with Firestore to retrieve data. I am interested in extracting only the data where a specific field in the collection from Firestore does not exist (is NULL). $query->where('FieldName', '!=&ap ...

Navigating the interface types between Angular, Firebase, and Typescript can be tricky, especially when working with the `firebase.firestore.FieldValue`

I am working on an interface that utilizes Firestore timestamps for date settings. export interface Album{ album_name: string, album_date: firebase.firestore.FieldValue; } Adding a new item functions perfectly: this.album ...

Issue with Firebase Functions trigger not activating

Just delving into the world of Firebase Functions for the first time using Typescript. I've written two functions: export const helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase!"); const testRe ...

Recommendations for Organizing Multiple "Isolated" Applications Using MVC 5 and Angular 2

We are currently managing a large MVC 5 ASP.NET 4.5.1 web application that follows the concept of treating each page as its own application due to the vast areas it covers. The existing pages are built using JQuery, regular Javascript, and Handlebars templ ...

Selecting options in combobox for each row in a table using Angular 2 programmatically

I am currently working on an Angular 2 application using TypeScript. In one of the tables within the application, there is a select control in one of the columns. The contents of this select control are bound to another string array. <table ngContr ...

Creating a Record instance consisting of a specific key and its corresponding value

Sorry for the complexity, I've struggled to simplify this further. Feel free to update the question title for more specificity. I aim to define a foundational data type structure: type AbstractBaseTypes = { [key: string]: { inputTypes ...

Passing a click event from a route-outlet to app.component in Angular 2

I'm brand new to using Angular 2 and developing an application app.routing.ts const appRoutes: Routes = [ {path:'', component:HomeComponent}, { path: 'login', component: LoginComponent }, { path: 'register&ap ...

What is the method for checking out sub, child, or inner components within a web browser?

In this screenshot, you can see the Left Panel where I have successfully generated the home component under the app component. I'm wondering how I can access or view this sub component inside the browser. When I try accessing it using http://localhos ...

Tips for displaying subtotal in a Vue application using Firebase Realtime Database

I am currently troubleshooting a method in my Vue app that is designed to calculate the total value of all items sold. Despite seeing the correct values in both the database and console log, the calculation seems to be incorrect. Could there be an issue wi ...

Tips for customizing the default name of the 'Page View' feature

After incorporating Angulartics2GoogleTagManager into the app.component, is it feasible to modify the default name of the tracked page view event from "Page View"? I require a different name than the current one. ...

Exploring Angular 2: How to loop through reactive form controls and set them as dirty

Is there a way to trigger the markAsDirty function for all the elements within a specific FormGroup in Angular? ...

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

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 ...

Attempting to deploy my Angular project on Heroku but encountering an error

While attempting to deploy my Angular project to Heroku, I followed all the necessary steps but encountered an error stating that the application failed to serve the page. As the application owner, it is advised to check the logs for more details. This can ...

Resolve the upstream dependency conflict that occurs during the installation of ng-bootstrap/ng-bootstrap

Encountering an error while attempting to install npm install --save @ng-bootstrap/ng-bootstrap. Seeking assistance in resolving this issue. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...

The Angular 2+ page fails to load properly on Internet Explorer or SharePoint

I created an Angular 5 solution that functions well in both Chrome and Firefox within SharePoint 2013. However, I have run into issues when using IE11. The index.html file was inserted into the SharePoint page using a Content Editor web part. Even after di ...

Identifying patterns within a string using JavaScript and TypeScript

Given a user-input pattern, for example [h][a-z][gho], and a string "gkfhxhk", I am attempting to determine if the string contains the specified pattern. The pattern dictates that the first character must be 'h', followed by any letter from a-z, ...

Utilize mui-tiptap to effortlessly upload images to your content

My current project involves using the mui-tiptap module in React 18 with Vite. Specifically, I am facing an issue with uploading a local image to my backend. The problem seems to lie in my frontend code, as I am encountering a TypeScript error that is prev ...

Learn how to display data from the console onto an HTML page using Angular 2

I am working on a page with 2 tabs. One tab is for displaying active messages and the other one is for closed messages. If the data active value is true, the active messages section in HTML should be populated accordingly. If the data active is false, th ...