Redirect if the canActivate function returns a false Observable<boolean>

In my Angular application, I have a reactive form that triggers a change in a Boolean value stored in a BehaviorSubject within a common service whenever the form value is updated.

I have implemented a route guard to prevent navigation based on the current value of the BehaviorSubject. If the value is true, navigation should be halted. However, my initial implementation does not seem to be working, indicating a possible issue with my subscription.

Component

onCreateGroupFormValueChange() {
    const initialValue = this.createGroupForm.value;
    this.createGroupForm.valueChanges.subscribe((value) => {
      this.hasUnsavedData = Object.keys(initialValue).some(
        (key) => this.createGroupForm.value[key] != initialValue[key]
      );
      this._helperService.onFormValueChange(this.hasUnsavedData);
    });
}

Service

private _unsaveDataSource = new BehaviorSubject<boolean>(false);
public unsavedForm$ = this._unsaveDataSource.asObservable();
onFormValueChange(hasData : boolean){
  this._unsaveDataSource.next(hasData);
}

Guard

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    
    return this._helperService.unsavedForm$.pipe(
      map(e => {
        if(e){
          return false
        }else{
          return true
        }
      })
    )
  }

Answer №1

I concur with the insight shared by Aluan Haddad. Utilizing the canDeactive Guard in Angular can help meet your desired outcome effectively. Check it out here: Angular CanDeactivate

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

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

Checking a String for a Specific Pattern in Angular 6 using Regular Expressions

urn:epc:id:sgln:345344423.1345.143 I need to verify if the string above, entered into a text box, matches the specified format consisting of (urn:epc:id:sgln) followed by numbers separated by two dots. ...

Angular - Subscribing to child route parameters at the exact moment when the child route becomes active

My webpage features a split screen design, and I need to access the folder ID from the parent route only when the child route is activated. The code snippet below works well in retrieving the correct parameters, but it throws a console error when loading t ...

Having trouble installing Angular CLI using npm command

After diligently following the steps outlined in the documentation here to install the Angular CLI, I encountered an issue. Upon running the command $ npm install -g @angular/cli in an empty directory, I was met with the following error message: npm ERR! ...

How can I determine the existence of an S3 bucket and, if it doesn't exist, create it using TypeScript CDK?

I am currently facing an issue where I need to verify the existence of a bucket in the account and either create a new one if it doesn't exist or use the existing bucket My attempt at achieving this is as follows: import {Bucket} from 'aws-cdk-l ...

What is the proper way to enhance properties?

In the process of developing a Vue3 app using Typescript, one of the components is designed to receive data through props. Initially, everything functioned smoothly with the basic setup: props: { when: String, data: Object }, However, I de ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

Although NgRx retrieves data from the API, it does not save it to the state

I've been struggling to grasp a fundamental concept in implementing ngrx. For instance, I have a situation where I need data from an API to validate information in my component, but once the validation is complete, I no longer need that data stored in ...

The functionality of Angular Datepicker is disrupted when scrolling through the page

Coding in HTML <div class="col-5 col-md-3 px-0 daterange-picker"> <div class="form-group"> <div class="input-group"> <input type="text" id="second ...

Discovering if a dynamic ng-template within Angular is loaded

I have successfully implemented a dynamic component loader. Now, I am looking for a way to determine when it is fully loaded in order to display it only after all images are downloaded. However, I have noticed that the event binding 'loaded' doe ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

What could be causing the Angular imports to not function properly?

I've recently set up a project, and it's compiling successfully. However, every time I attempt to add a directive like [formGroup], it throws an error such as "Property formGroup is not provided by any applicable directives nor by form element". ...

Contrasting covariant and contravariant positions within Typescript

I'm currently diving into the examples provided in the Typescript advanced types handbook to broaden my understanding. According to the explanation: The next example showcases how having multiple potential values for the same type variable in co-var ...

Transforming Angular 2 quickstart application for deployment on Google Cloud infrastructure

Attempting to deploy a basic project on Google Cloud platform has proven to be more challenging than expected. The simple quickstart project can be accessed here, and functions flawlessly locally. While there are other providers like Heroku that offer one ...

Creating intricate mazes using canvas drawing techniques

I recently developed a maze generator as a personal project utilizing a graph. While the generation logic works perfectly, I am facing challenges when it comes to rendering the maze. In my approach, each cell is represented by an array of 4 edges where the ...

Error: Promise was not caught: Unable to find any routes

I recently delved into learning Angular2 and started working on a sample project where I needed to navigate between three different pages. In order to set up the routing, I configured a RouterModule within the app.module.ts file as shown below: @NgModule ...

Determine characteristics of object given to class constructor (typescript)

My current scenario involves the following code: abstract class A { obj; constructor(obj:{[index:string]:number}) { this.obj = obj; } } class B extends A { constructor() { super({i:0}) } method() { //I wan ...

React type-script does not trigger the onClick event for CheckBox

I have created a custom component called MyCheckBox (which I am using as a helper component). I imported this component into another one, but for some reason, the event is not being triggered when I try to click on it. Here is the code for reference: MyC ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...