Encountering a 'Map function not defined' error following the update of Angular and AngularFireAuth

After updating my code from Angular 2 to Angular 5 and also updating the AngularFireAuth package, I encountered a problem that has been puzzling me.

Although there are no compile errors with the .map function below, I am seeing a 'map is not a function' error in the console. I need to understand the changes between Angular 2 and Angular 5, as well as what modifications I should make now.


import { AngularFireAuth } from 'angularfire2/auth';
import { CanActivate, Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { GlobalController } from '../services/globalController.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private authService: AngularFireAuth, private router: Router, private global: GlobalController) { }
    
    canActivate(): Observable<boolean> {
        return this.authService.authState.map(user => {
            if (user && !user.isAnonymous) {
                this.global.setUserEmail(user.email);
                this.global.setUserID(user.uid);
                this.global.setUserName(user.displayName);
                this.global.setUserPhoneNumber(user.phoneNumber);
                
                if (user.photoURL == null) {
                    console.log('No Photo Found.');
                    this.global.setUserPhotoLink(this.global.getDefaultPhotoLink());
                } else {
                    this.global.setUserPhotoLink(user.photoURL);
                }
                
                console.log('User Photo Url:' + user.photoURL );
                return true;
            }
            
            this.global.ChangeState(this.global.GlobalStates.preLogin);
            return false;
        });
    }

}

Console Log Error "map is not a function"


ERROR Error: Uncaught (in promise): TypeError: 
this.authService.authState.map is not a function
TypeError: this.authService.authState.map is not a function
at AuthGuard.canActivate (auth-guard.service.ts:14)
...

Answer №1

The issue arose when I decided to update RxJS to version ^5.5. This change was necessary due to the shift in RxJS towards lettable operators for better tree shaking and simplified custom operator creation, requiring me to adjust my code accordingly.

A helpful guide can be found here.

To summarize, I made changes to my import statement:

import 'rxjs/add/operator/map';

Changed it to:

import { map } from 'rxjs/operators';

I also included a .pipe wrapper in the section.

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AngularFireAuth,  private router: Router, private global: GlobalController) { }
canActivate(): Observable<boolean> {
    return this.authService.authState.pipe(
         map( user => {
            if (user && !user.isAnonymous) {
                this.global.setUserEmail(user.email);
                this.global.setUserID(user.uid);
                this.global.setUserName(user.displayName);
                this.global.setUserPhoneNumber(user.phoneNumber);
                if (user.photoURL == null) {
                    console.log('No Photo Found.');
                    this.global.setUserPhotoLink(this.global.getDefaultPhotoLink());
                }else {
                    this.global.setUserPhotoLink(user.photoURL);
                }
                console.log('User Photo Url:' + user.photoURL );
                return true; }
            this.global.ChangeState(this.global.GlobalStates.preLogin);
            return false;
    }));
}

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

What is the best way to showcase the character and word count on the Redactor rich text / html editor?

Recently, I made the decision to switch from CKEditor to Redactor due to numerous issues with AJAX updates on the DOM. In the past, we relied on a CKEditor plugin for character count in our rich text editor. Is there a way to implement this same feature ...

What is the best way to arrange an array of objects in JavaScript by numerical order and then alphabetically?

Possible Duplicate: Sorting objects in an array by a field value in JavaScript I'm looking to sort an array of objects both numerically (by id) and alphabetically (by name). However, the current method I'm using is not giving me the desired ...

Create a toggle effect similar to jQuery using JavaScript

Looking for pure JavaScript code to implement show/hide functionality similar to jQuery. Currently, I am using the following code: y=document.getElementById('regform').style.display; if (y == 'block'){ document.getElementById(&apo ...

How to troubleshoot Django's Jquery datatable aoData not functioning issue

Getting Started with Datatable Initial Data Setup object_list=[{'username': u'Paul', 'phone_number': u'9910087044', 'user_group__name': '', 'manager_name': ' ', 'role&ap ...

Store the image URL in cache during AJAX loading

I have implemented an ajax slider to display images, and it is functioning perfectly. However, I am facing an issue with image caching. Since the images change dynamically using ajax, there is no cache available which causes a delay in displaying the new i ...

Tips for creating a curved shape using fabric.js

I am encountering an issue while trying to draw an arc using a circle with a start and end angle in my code. Here is the snippet I am working with: var circle = new fabric.Circle({ radius: 30, left: 20, top: 20, fill: " ...

Retrieving latitude and longitude coordinates to determine percentage-based or pixel-based x and y positions

I'm currently working on extracting percentage or pixel coordinates from a latlng in leaflet maps. Here is the code snippet that sets up the map and tile layers (adapted from an app named 'maptiler') var mapMinZoom = 0; var mapMaxZ ...

I'm looking to generate a semicircle progress bar using jQuery, any suggestions on how

Hi there! I'm looking to create a unique half circle design similar to the one showcased in this fiddle. Additionally, I want the progress bar to be displayed in a vibrant green color. I've recently started learning about Jquery and would apprec ...

Button click triggers CSS animation

Check out the interactive demo $(document).ready(function(){ $('#btn-animate').click(function(){ animate(); }); $('#btn-remove').click(function(){ $('.to-animate').removeClass('animate'); }); func ...

Design a hover zone that allows for interaction without disrupting click events

I am looking to create a tooltip box that appears when hovering over an element, and I want the tooltip to only disappear when the user's mouse exits a specific custom hover area outlined by a vector graphic. My current implementation is working, but ...

When the "ok" button is clicked in a custom confirmation box, the function will return

When the first button is clicked, I validate certain text boxes and then call Confirm() to display a confirmation box. I want it to return true to the calling function when "ok" is clicked and for control to go back to the UI to proceed ...

What steps do I need to follow in order to set the language of the npx bootstrap datepicker to pt

I have been working on a project using Angular 4, where I incorporated ngx bootstrap for date picker functionality. However, I encountered an issue with the date picker being displayed in English. In an attempt to rectify this, I added the following lines ...

Establishing the earliest date on the X Axis in a scatter plot created with ChartJS

When plotting my data points with numerical values for the Y coordinate and date values for the X coordinate, I noticed that the scatter plot starts the X axis at 1976 even though my earliest date is in 2018. Is there a way to set the starting value of the ...

The error code 413 payload too large was encountered when trying to process a base64 string in express,

I attempted to send a post request to my node server with a base64 encoded file. After encountering a PayloadTooLargeError: request entity too large exception, I decided to increase the payload limit using Express 4 convention: app.use(bodyParser.json({l ...

Use the jQuery .GET() method two times to retrieve data and obtain the outcomes

My code involves making a series of GET calls where the returned data from one call is used in another call before returning the final results. However, I want to ensure that my program waits until all the data is retrieved. This is what I have come up wi ...

Ensure that the interface limits the key value to match precisely the value of a constant in Typescript

Seeking assistance in understanding how to enforce a specific type for an optional key within an interface: const FIRST = "FIRST" const SECOND = "SECOND" interface TSomeInterface { element: Element order?: typeof FIRST | typeof ...

Tips for changing the state of a toggle button with JavaScript

I need help creating a toggle button. To see the code I'm working on, click here. In my JavaScript code, I am reading the value of a 'checkbox'. If the value is true, I add another div with a close button. When the close button is clicked, ...

Is it true that Vue 3 + Inertia automatically removes event listeners upon component unmounting?

There is an event listener set up within the script setup block: <script setup> import {ref} from 'vue' const elementRef = ref(null) window.addEventListener('click', (event) => { if (!elementRef.value.contains(event.t ...

A guide on resolving TypeScript monorepo webpack loader problems

I recently created a typescript monorepo here with the following organized folder structure: . └── packages ├── package.json // Contains the monorepo workspace configuration ├── web-app // Includes the NextJS website files └ ...

What is the methodology for obtaining the setter property type in TypeScript?

Describe a scenario where an object contains both getter and setter methods with different types. How can we determine the type of the setter function? Consider defining an object with getter and setter functions like the example below: type Foo = { g ...