Why am I encountering this issue? The "map" property does not appear to be available for the type "Observable<boolean>"

I have been working on an Angular project where I am utilizing an AuthGuard class to prevent unauthorized access to protected pages. Despite following an online course, I encountered the following issue:

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { AuthService } from './auth.service';
import 'rxjs/Rx';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs';

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router:Router) {}

  canActivate(route: ActivatedRouteSnapshot,
                     state: RouterStateSnapshot): Observable<boolean>  {

    return this.authService.authInfo$
                           .map(authInfo => authInfo.isLoggedIn())
                           .take(1)
                           .do(allowed => {
                             if(!allowed) {
                               this.router.navigate(['/login']);

                             }
                           })
  }

}

In my AuthService class, I simply declared the following property:

authInfo$:Observable<boolean>;

The problem arises in my AuthGuard class, where I receive an error message on this particular line:

.map(authInfo => authInfo.isLoggedIn())

The error states:

Property 'map' does not exist on type 'Observable'.ts(2339)

Despite importing the import 'rxjs/add/operator/map' operator, I cannot figure out why this error is occurring. What could be causing this? How can I resolve this issue?

Answer №1

To enhance your code, consider including the pipe .pipe(map()...)

this.authService.authInfo$
                          .pipe(
                           map(authInfo => authInfo.isLoggedIn()),
                           take(1),
                           do(allowed => {
                             if(!allowed) {
                               this.router.navigate(['/login']);

                             }
                           })
                          ) // end of pipe

Answer №2

When looking at older code examples, you may still come across rxjs flow written like this:

observable$
  .map(val => mapToSomething(val))

However, in more recent versions of rxjs, the preferred method is to use operators within a pipe:

// Don't forget to import the operator!
import { map } from 'rxjs/operators';

observable$
  .pipe(
    map(val => mapToSomething(val))
)

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

Managing dependencies and automating setup processes can be tricky when incorporating Typescript into a

Query: How can I easily set up Typescript with Symfony without making extensive changes to Symphony's configuration files? Here are the key requirements for the solution: Typescript MVC Pattern should be set up in a private typescript directory: ...

Encountering Errors while executing the yarn build or tsc commands

Whenever I attempt to build a project or run the yarn tsc command, I encounter various types of errors. This seems to be due to them being installed in the incorrect location. But what could be causing this issue? Feel free to ask for more details if nee ...

Guide to creating a function and exporting it to a component in react with the help of typescript

I have a ParentComponent where I need to integrate a function from a separate file and incorporate it into the ParentComponent. The structure of the ParentComponent is as follows: function ParentComponent() { const count = 5; // this value usually co ...

Passing objects to Angular 4 routes while maintaining Query Params unchanged

I'm currently working with Angular 4 and I need to pass an object to the router without updating query parameters. user.component.ts this.router.navigate(["/profile",{ action: 'edit', user: {id: 1, name: 'test', email: &apo ...

What are the pros and cons of defining `[defaultColor]="'violet'"` in Angular 2?

If you visit the advanced section of angular.io documentation, you will come across the following code snippet: <p [myHighlight]="color" [defaultColor]="'violet'"> Highlight me too! </p> It made me wonder, when binding to a consta ...

What prevents us from returning Observable.of(false) in the catch block within the canActivate function?

In order to protect certain routes (admin), I utilize the canActivate feature. In this scenario, I employ an authGuard class/function: The issue arises when attempting to return an observable of boolean using: return Observable.of(false);. This approach d ...

Explain the interaction of cookies between Angular and C# controllers

Can anyone provide clarity on how cookies are utilized between an angular application and a C# server controller? After looking through various discussions and forums, here's what I've gathered: The angular client initiates an HTTP Request (e. ...

Updating part of an object using TypeScript

I am looking to create a utility function that takes an instance and an object as input, and then updates the instance with the values from the provided object fields. Below is the code for the utility function: function updateEntity<T, K extends keyof ...

Implement Angular's Observable Subscription to fetch data from an API endpoint

Forgive me if I'm not using the correct terminology for Subjects and Observables. I am currently trying to subscribe to newImages in order to get a list of images. In my console, the response is as follows: [] [3] [7] [9] Each number represents ...

Is casting performed by <ClassName> in typescript?

According to the Angular DI documentation, there is an example provided: let mockService = <HeroService> {getHeroes: () => expectedHeroes } So, my question is - can we consider mockService as an instance of HeroService at this point? To provide ...

Navigating in express

Here is the structure I am working with: server.ts routes/ index.ts homeRoute.ts In server.ts: let app = Express(); app.use(router); In routes/index.ts: const routes = Router(); export default function router() { routes.use('/home' ...

The type 'Element | undefined' cannot be assigned to the type 'ReactElement<any, any> | null'

Important Note about Components and Files: Explanation of types.ts File: export interface IIcon { iconName: string; iconSize: string; iconFill: string; } Clarification regarding index.tsx File: import React, { FC } from 'react'; import { ...

understanding the life cycle of components in Ionic

I created a component with the following structure: export class AcknowledgementComponent implements AfterViewInit { private description: string; @Input('period') period: string; constructor() { } ngAfterViewInit() { console.log ...

Expanding properties in a React component based on certain conditions using TypeScript

I am attempting to dynamically expand my component props based on whether a specific prop is included. The goal is to add attributes from an anchor if the href prop is provided, and include attributes from a button if it is not. Is this achievable? Chec ...

Utilizing symbols as a keyof type: A simple guide

Let's consider the following: type Bar = keyof Collection<string> In this scenario, Bar denotes the type of keys present in the Collection object, such as insert or remove: const x: Bar = 'insert'; ✅ But wait, the Collection also c ...

Validating minimum and maximum values with Angular 2 FormBuilder

I am currently developing a form using Angular 2 Formbuilder and I want to ensure that users can only input positive values into the amount field (with a minValue of 0 and maxValue of 100). How can I go about implementing minimum and maximum value validati ...

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

Is it possible to extract specific columns from the Convex database?

I am looking to retrieve all columns from a table using the following code snippet. Is there a more efficient way to achieve this? I couldn't find any information in the documentation. Does anyone have a workaround or solution? const documents = await ...

Ensure that the tooltip remains visible within the confines of the page

In my Angular application, I have successfully implemented a versatile tooltip feature that goes beyond just displaying text. The tooltip is a div element that has the ability to contain various contents: .tooltip-master { position: relative; .tooltip ...

Error: Attempting to access 'pageContext' property on undefined object, resulting in TypeError while utilizing sp pnp v3

I am currently following a tutorial to build a webpart using SPFX and SP/PNP v3: https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/use-sp-pnp-js-with-spfx-web-parts I have also consulted: Here is the main .ts file: public async onIn ...