How to extract a value from a BehaviorSubject within an Angular 6 guard

I have chosen this approach because I have another guard responsible for validating the user based on a token that was previously stored. This is how it was handled in previous versions of rxjs, but now with the latest version you can no longer use map on the subject.

canActivate(next: ActivatedRouteSnapshot,
           state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.authservice.behaviorsubject().map(x => {
    if (x) {
      return true;
    } else {
      return false;
    }
  })
}

I need guidance on how to make this work. I attempted something like this, but it does not return anything since it was never subscribed to (and also it's not an Observable, it's an AnonymousSubject when logged into console).

canActivate(next: ActivatedRouteSnapshot,
           state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.authservice.behaviorsubject().pipe(
    map(x => {
      if (x) {
        return true;
      } else {
        return false;
      }
    })
  )
}

I also tried converting it into an observable using Observable.create(), but it didn't work. I know I'm missing something. Help please :)

Answer №1

To make your behaviorSubject an observable in your authService, you can do the following:

private _authenticated: BehaviorSubject<boolean> = new BehaviorSubject(null);

behaviorAsObservable(): Observable<boolean> {
   return this._authenticated.asObservable();
}

Just a quick note: CanActivate works well with observables, so if your behaviorAsObservable method already returns an Observable of type boolean, there's no need to map it again.

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

Tips for creating a draggable Angular Material dialog

Has anyone been able to successfully implement draggable functionality in an Angular Material Dialog? I've spent a considerable amount of time searching for a definitive answer but have come up empty-handed. Any insights or guidance would be greatly a ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...

Combining two arrays of names and values into a fresh object using Javascript

Trying to merge two arrays, one for column headers: cNames = ["Year","Count"] And another for data: mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143] The goal is to combine them like this: [ { Year: "2005", Count: 5021 ...

Timepicker.js - Incorrect Placement of Time Picker in Certain Scenarios

Utilizing the timepicker.js library to select a time, I am encountering an issue. When clicking on the input field, the timepicker should appear next to it. This function works as expected when the input is within the main view of the document. However, if ...

Experiencing problems with malfunctioning javascript tabs

As a beginner user and coder, I'm currently working on creating a portfolio website. I had the idea to implement tabs that would allow for content swapping, but unfortunately, I'm having trouble getting the JavaScript to function correctly. I at ...

Node.js QuickStart guide for authenticating with the Youtube API encounters error

Using node.js for a Discord bot, I encountered an issue with Google's API tutorial being outdated. Here is the link to their tutorial. The tutorial asks to select an "Other" option which no longer exists, now replaced by "desktop app". This was an ea ...

Tips for preventing the need to create a function within a loop

Currently, I am in the process of collecting data through REST calls. I have created a function that accesses a "directory" endpoint to retrieve a list of individuals. While I can easily obtain details about their children, I need to make individual AP ...

The importance of variables in Express Routing

I'm really diving into the intricacies of Express.js routing concepts. Here's an example that I've been pondering over: const routes = require('./routes'); const user = require('./routes/user'); const app = express(); a ...

Ecommerce Template for Next.js

I am new to the world of web development and I have a project involving customizing a Next.js ecommerce template. Since I'm still learning programming, I would appreciate a simple summary of the steps I need to take in order to achieve this. The speci ...

Row Model for Server-Side Processing

Looking to maintain the default loading overlay while serverSideRowModel functions are invoked in my Angular app, and prevent the loading spinner from showing up during data fetching. ...

What is the best way to determine if a radio button has been chosen, and proceed to the next radio button to display varied information?

The goal is to display the <div class="resp"> below each radio button when it is selected, with different content in each <div class="resp">. The previously selected <div class="resp"> should be hidden when a new radio button is chosen. O ...

Is it possible to directly add a child in HTML from nodejs?

I'm in the process of developing a chat application that requires users to select a room from a list of available rooms stored in <datalist> options, which are fetched from a SQL table on the server. Within my login.html file, users are prompte ...

Sub-objects in Angular 2 with observables

I need guidance on understanding Observables/Subjects in Angular2. My app includes data of the following structure: sections = [ { _id: '999' name: 'section 1' items: [ { name: "i ...

Encountering a TypeError stating that the "option is undefined" error has occurred

Unexpectedly, my dropdown menu that was functioning perfectly fine is now throwing an error. I've made several changes and none of them seem to resolve the issue. Could it be a data type mismatch or am I missing something crucial here? Your insights ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

Angular 2: Converting JSON data into an array

I am working with JSON data that contains vendor fields and I need to extract unique vendors into an array. Can someone provide guidance on how to achieve this in an Angular2 component? Here is the sample data: [{"category": "Living Room", "vendor": "Fle ...

What is the reason that when the allowfullscreen attribute of an iframe is set, it doesn't appear to be retained?

Within my code, I am configuring the allowfullscreen attribute for an iframe enclosed in SkyLight, which is a npm module designed for modal views in react.js <SkyLight dialogStyles={myBigGreenDialog} hideOnOverlayClicked ref="simpleDialog"> <if ...

Styling the pseudo element ::part() on an ion-modal can be customized based on certain conditions

Looking for a solution regarding an ion-modal with specific CSS settings? I previously had the following CSS: ion-modal::part(content) { width: 300px; height: 480px; } Now, I need to adjust the height based on conditions: if A, the height should be lo ...

Maximizing the performance of plotting hundreds or thousands of series in a 2D scatter or line chart using Echarts

Plotting a large data set with hundreds or thousands of series using Echarts has proven to be slow and challenging to manage. If you take a look at the example code provided in this large and progressive options on single series instead of all plotted se ...

Issues with CKEDITOR in Internet Explorer when multiple instances are used with different configuration files

My current challenge involves placing multiple CKEDITOR instances on a single page, each loading a different configuration file. While it functions correctly in Firefox (FF), Internet Explorer (IE) seems to apply the config file from the last instance on t ...