Accessing app state in angular guard using NGRX - What is the procedure?

In my route guard(canActivate), I am looking to access the current state of my app in order to validate data and prevent users from navigating incorrectly. How can I retrieve the current state?

I attempted using a subscription on the store to obtain the state, but it only retrieves the data when the state is modified!

Answer №1

If you want to make use of the canActivate method effectively, it's essential to ensure that you return a boolean value. One way to achieve this is by mapping your store data to a boolean value.

import { of } from 'rxjs';
import { switchMap } from "rxjs/operators";

@Injectable()
export class SomeGuard implements CanActivate {
    constructor(private store: Store<AppState>) {}

    loadData(): Observable<any> {
        return this.store.select(state => state.someState);
    }

    canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
        return this.loadData()
            .pipe(switchMap(() => {
                return of(true);
            }));
    }
}

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

Utilizing Angular2 Guard to Ensure False IdentityServer4 OIDC Security

After successfully authenticating a user and redirecting them back to the main site, the following code runs: <script src="https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.2.2/oidc-client.min.js"></script> <h1 id="waiting">Waiting... ...

Customizing data input in ngx chart's bubble chart is essential for creating a unique

For my project, I utilized the ngx-chart bubble chart. However, I encountered an issue when the data was in the following format: multi: any[] = [{ "name": "Kuwait", "series": [{ "name": "a", "waiting time": 24, "real time": 38, "queue size": 31 }, { " ...

Executing a Javascript function through Typescript in an Ionic application

I integrated a plugin into my ionic project, which includes both Java and JS code: cordova.define("cordova-sms-plugin.Sms", function(require, exports, module) { 'use strict'; var exec = require('cordova/exec'); var sms = {}; functio ...

Using static typing in Visual Studio for Angular HTML

Is there a tool that can validate HTML and provide intellisense similar to TypeScript? I'm looking for something that can detect errors when using non-existent directives or undeclared scope properties, similar to how TypeScript handles compilation er ...

How come the action doesn't trigger in my React/Redux application?

Currently, I am in the process of developing a small application that incorporates modals. Instead of relying on pre-made packages like react-modal, I have taken the initiative to build the modal functionality from scratch. 1) Defining a reducer located i ...

Edit the CSS styles within a webview

When loading the page in NativeScript using web viewing, I encountered a need to hide certain elements on the page. What is the best way to apply CSS styles to HTML elements in this scenario? Are there any alternatives that could be considered? I have been ...

The variable 'key' is declared in the Google Chrome extension V3 local storage, but it appears that its assigned value is never actually accessed

In my TypeScript code, I have defined a function like so: setLocalStorage: async (key: string, value: string): Promise<string> => { return new Promise((resolve, reject) => { chrome.storage.local.set({ key: value }, funct ...

Minimize overlap across both projects

One scenario is having two projects that utilize a lot of the same components. How can we minimize redundancy between them? Is there a way to make them shareable? Perhaps leveraging webpack could be the solution? ...

Leveraging Font Awesome and Material Icons within ngFor in Angular 2

I have a unique situation where I need to display a dynamic list of icons in a right side bar. These icons are added to the sidebar based on user actions and are displayed using the ngFor directive. The challenge here is that some icons come from Font Awe ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

Controlling the DOM with Angular 2

I am currently developing a website in Angular 2. I have successfully implemented a JQuery code that adds 2 input fields and 1 delete button when a custom button is clicked. When the user clicks on the delete button, it removes the inputs by manipulating t ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

Angular6 ng test is not successful

I recently upgraded my project from Angular4 to version 6. Everything seems to be working fine, except for the issue with running ng test: ERROR [karma-server]: Server start failed on port 9876: Error: No provider for "framework:@angular/cli"! (Resolving ...

Using TypeScript to narrow down types within mapped types

Can you create a mapped type based on the property type? For example, if I want to map all properties with type String to Foo and all other types to Bar. Can this be done like this: type MappedType<T> = { [P in keyof T]: T[P] === String ? Foo : B ...

Centering form fields in ReactJS using Material UI

I'm currently facing a challenge trying to center-align my react form. Below is the structure of my form: The technology I am using is Material UI for ReactJS <Grid item xs={12}> <Grid item xs={12}> <FormGroup ...

Using React MUI Select in combination with react-hook-form does not seem to be compatible with Cypress testing

Within my React application, I have implemented a form that includes a dropdown select. Depending on the option selected from the dropdown, different input fields are rendered. const [templateType, setTemplateType] = useState(""); const { regi ...

The index.js file from Heroku NodeJS is being delivered as a response instead of being run

I have a GitHub repository that functions properly on my local machine using 'npm start' or 'heroku local web', but when deployed to Heroku, it only displays the contents of the dist/index.js file instead of executing it. This applicat ...

Mongoose failing to persist subdocument

After trying to insert into my collection, I noticed that the sub-document is not being saved along with it. This issue has left me puzzled. This is the scheme/model I am working with: import { Schema, Document, Model, model } from 'mongoose' ...

I am interested in updating the content on the page seamlessly using Angular 6 without the need to reload

As a newcomer to Angular, I am interested in dynamically changing the page content or displaying a new component with fresh information. My website currently features cards, which you can view by following this Cards link. I would like to update the page ...

Implementing Observable lambdas in Angular templates for easy function calling

Within a component, I have the following code snippet: public hasFoo$: Observable<(name: string) => boolean> = ... Now, I would like to use this multiple times in my template with a stepper: <mat-vertical-stepper> <mat-step *ngIf="ha ...