Route protection is ineffective when dealing with two observables simultaneously

After writing the route guard as shown below, I encountered an issue with the else statement that was not returning a result, even though it should have. Surprisingly, there were no errors either.

this.hotelSettingsService.get().pipe(map(res => {
          if (res) {

By removing the

from(this.localStorageService.get(LocalStorage.SCROLL_VIEW_HOLDER)).pipe(map(path)
section, the code started working.

I suspect that I might have made a fundamental mistake. Any insights on this?

Check out a video demonstrating this behavior: Video

 canActivate(): Observable<boolean> {

    return from(this.localStorageService.get(LocalStorage.SCROLL_VIEW_HOLDER)).pipe(map(path => {
      if (path) {
        this.router.navigate(path);
        return true;
      } else {
        this.hotelSettingsService.get().pipe(map(res => {
          if (res) { // not come to here
            this.router.navigate([this.getLandingPage(environment.hotelName)]);
            return true;
          }
        }), catchError((err) => {
          return of(false);
        }));
      }
    }), catchError((err) => {
      return of(false);
    }));
  }

Adding a return seems to resolve the issue:

https://i.stack.imgur.com/hb1rq.png

This simplified version is functioning properly:

canActivate(): Observable<boolean> {

        return this.hotelSettingsService.get().pipe(map(res => {
              if (res) { 
                this.router.navigate([this.getLandingPage(environment.hotelName)]);
                return true;
              }
            }), catchError((err) => {
              return of(false);
            }));
          }
     }

Answer №1

To start, ensure that you include the return keyword before this.hotelService...., just like shown in your provided image. Additionally, make sure to flatten the result by utilizing switchMap instead of map:

 canActivate(): Observable<boolean> {
    // Flattening the result due to a possible inner observable
    return from(...).pipe(switchMap(path => {
      if (path) {
        this.router.navigate(path);
        // Return an observable true value
        return of(true);
      } else {
        return this.hotelSettingsService.get().pipe(map(res => {
          if (res) {
            this.router.navigate([this.getLandingPage(environment.hotelName)]);
            return true;
          }
        }), catchError((err) => {
          return of(false);
        }));
      }
    }), catchError((err) => {
      return of(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

Tips for checking dropzone functionality during development

I'm currently working on an Angular 5 application and incorporating dropzonejs (the angular wrapper) into it. However, as I am not the backend developer, I do not have full visibility into how the backend has been developed. Currently, CORS is being ...

It seems like the recent upgrade to yarn 2 has caused issues with typescript types, whereas the installation of the same project with yarn 1 was

Recently, I've been attempting to update a typescript monorepo to utilize yarn 2, but I've encountered an issue where typescript is struggling to recognize certain react props. This functionality was working fine in yarn 1.x, leading me to believ ...

Typescript is facing an issue locating the declaration file

I'm encountering an issue with TypeScript not recognizing my declaration file, even though it exists. Can anyone provide insight into why this might be happening? Here is the structure of my project: scr - main.ts - dec.d.ts str-utils - index. ...

Exploring Vue with Typescript - leveraging components without explicit definitions

Has anyone successfully used vue-instant component as a child component before? I'm having trouble adding components without definition. Could it be related to webpack config ignoring node_modules due to lack of type declaration? Here's the code ...

Distinguishing the switch function from the React switch operator (jsx, tsx)

We are in the process of converting our portfolio from JavaScript to TypeScript, utilizing NextJS as the frontend framework and Strapi as the backend. To enable dynamic content, we have implemented a dynamiczone field within the post model that is accesse ...

What steps can I take to resolve a dependency update causing issues in my code?

My program stopped working after updating one of the dependencies and kept throwing the same error. Usually, when I run 'ng serve' in my project everything works fine, but after updating Chartist, I encountered this error: An unhandled exception ...

AmCharts stacked bar chart - dynamically adjust value visibility (adjust transparency) based on user interaction

I recently utilized amcharts to construct a bar chart. The creation of my stacked bar chart was inspired by this specific example. Currently, I am attempting to modify the alpha (or color) of a box when hovering over another element on my webpage, such as ...

Issue with Angular not sending data to ASP.net server

Attempting to send data to my asp.net server using angular. After testing the front-end data, the issue arises when sending the data with a post request; angular sends null data instead. Interestingly, when sending the same data to the server from Postman, ...

Identifying an SCSS file based on its class name in Angular

Currently, I'm utilizing an Angular 5 application with styles that are encapsulated within components. Upon running the ng serve command, all styles get inserted into <styles> tags within the <head> section of the page. This results in br ...

The occurrence of a loading error arises when attempting to load the second component, displaying the message 'The template instructed for component SidebarComponent is

My journey with Angular has just begun, and I decided to challenge myself by creating a simplistic dashboard. In order to achieve this, I developed two components called DashboardComponent and SidebarComponent. The DashboardComponent loads smoothly witho ...

Creating a variable name dynamically using Typescript

I am looking to efficiently create multiple instances of variables and assign values in a single statement, an example of which is shown below. this.myList1[data.id] = data.id + "-" + data.desc; this.myList2[data.id] = data.id + "-" + data.desc; this.myLi ...

The output.library.type variable in WebPack is not defined

Currently, I am delving into WebPack with a shortcode. As part of my learning process, I am working on a code snippet that involves calculating the cube and square of a number, which are then supposed to be stored in a variable outlined in the webpack.conf ...

Is there a way to make sure video files are downloaded instead of automatically playing in the browser window?

I have a link to a video file with various formats like mp4, 3gp, etc. When I click on the link, it opens in the same tab. Changing the target attribute to "_blank" makes the video open in a new tab. However, when I ctrl-click the link, the file s ...

Issues Encountered when Installing Angular on a Mac

While attempting to install angular on my MacBook, I encountered some confusing errors. Below is a snippet of the terminal commands I used: S-MacBook-Pro-491:~ s$ node -v v8.9.4 S-MacBook-Pro-491:~ s$ npm -v 5.6.0 S-MacBook-Pro-491:~ s$ npm install -g @a ...

Extract the content of a nested JSON object in ReactJS using map function

I am encountering an issue while attempting to map nested JSON data, specifically the error 'Element implicitly has an 'any' type'. The problem arises within the search component at: Object.keys(skills[keyName]).map() Below is the cod ...

Encountered an issue when utilizing the useRef hook in Next.js version 13

I am currently exploring nextjs13 and typescript. I encountered an issue when attempting to use the useRef hook. Below is the code snippet in question: import { useEffect, useRef } from "react" export const useDraw = () => { const canvas ...

tsc will automatically incorporate additional files

I'm grappling with a frustrating issue related to tsc that's really getting to me. The problem involves having a file b.ts in the src folder, and another file a.ts in the project root folder. Here is an excerpt of my tsconfig file: { "comp ...

Set up the configuration for express to access an external API through proxy.conf.json while in production mode

I am currently managing two applications on Heroku, one being myserverapi (built with Spring Boot) and the other being a client-side Angular app named client. The server is hosted at myserver.heroku.com while the client resides at myclient.heroku.com. At t ...

Saving the name and corresponding value of a selected option element into separate fields using Angular framework

I have implemented the following code to generate a select field. The ngModel is successfully updating the value, but I am also looking to capture the name of the selected option and store it in a different field. Is there a solution to achieve this? ( & ...

Implementing NestJS: Integrating TypeORM Datasource without relying on class dependency injection

I have a unique situation that requires some help. Our team is in the process of integrating nestjs into our current express codebase. Previously, we were using Typeorm 0.2 and recently upgraded to 0.3. Due to the fact that we utilize functions instead of ...