Tips for transferring Subscription content to CanDeactivateGuard

I have a CanDeactivateGuard set up for my routes, and I am looking to pass data to it. The guard is designed to prompt users to save any unsaved changes before navigating away. The data that needs to be passed into the dialog comes from a Subscription.

I came across this helpful answer while trying to find a solution: How to pass parameters to constructor of canActivate?

However, it seems a bit too simplified for my specific scenario because I need to pass a Subscription along with my routes, which poses a challenge.

This is the current implementation of my guard:

export class PendingChangesGuard
  implements CanDeactivate<ComponentCanDeactivate> {
  constructor(
    private myDialogService: MyDialogService,
  ) {}

  canDeactivate(
    component: ComponentCanDeactivate,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot
  ): boolean | Observable<boolean> {
    return component.canDeactivate() || this.openConfirmDialog();
  }

  openConfirmDialog() {
    const ref = this.myDialogService.open(MyDialogComponent, /** Pass a CONFIG object here **/);
    return ref.afterClosed$();
  }
}

In the modalDialogService.open() method, the goal is to pass data as the second argument.

For fetching the necessary content in another component using different data from the same service call, I have implemented it like so:

export class MyComponent implements OnInit, OnDestroy {
  myContent: any;
  myContentSubscription: Subscription;
  constructor(private myContentService: MyContentService) {}

  ngOnInit() {
    this.myContentSubscription = 
this.myContentService.myContent$.subscribe(
      flag => {
        if (flag) {
      this.myContent = this.myContentService.getMyContent();
        }
      }
    );
  }
}

The myContentSubscription will populate the necessary data required for opening the modal. However, I believe that the Guard should not handle the service call. Additionally, due to the asynchronous nature of the call, there needs to be a way to wait before passing the data into the modal.

Where would be the appropriate place to place the subscription code so that the Guard can access it when invoked?

Answer №1

For anyone facing a similar issue, here is how I solved it:

Upon the application's initialization, the app.component.ts triggers the HomePageTridionContentService. By the time my Guard needs to act, the service has already fetched the necessary data. In order to access this data in the Guard, all I had to do was implement the following method:


openConfirmDialog() {
    const modalData = 
this.homePageContentService.getModalContent();
    const config = { data: { ...modalData } };
    const ref = this.modalDialogService.open(ModalDialogComponent, 
config);
    return ref.afterClosed$();
}

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

How can I load a separate component.html file using a component.ts file?

Hey there, I'm a beginner with Angular and I have a question about loading a different home.component.html file from a method within books.component.ts. Here's the code snippet from my books.component.ts file: import { Component, OnInit } from ...

Using the `window` object in Jasmine with Angular, a mock can be created for testing purposes

In my current project, I have a function that I need to write unit tests for. Within this function, I am comparing the global objects window and parent using const isEqual = (window === parent). I am wondering what would be the most effective way to mock ...

What is the reason behind the checkbox event status returning the string "on" rather than true/false?

I have implemented a custom checkbox as a child component within a parent component. I properly pass the ngModel, name, etc., and attempt to update the model with a boolean status (true/false) based on the checkbox status using an EventEmitter. However, t ...

The joinAndSelect function in NestJS is having trouble fetching all the data from the PostgreSQL database

In my database, I have three tables named product, branch, and product_branches. The product table contains columns: id, name The branch table contains columns: id, name, lat, lng And the product_branches table contains columns: productId, branchId I w ...

Activate function upon closure of window.open

I'm facing an issue where I need to load a URL in window.open that saves some cookies in my browser. After the window.open is closed, I want to access those cookies but I haven't been able to find a way to do it. I've tried the following cod ...

URL Transformation Post Removal of Child Component

I'm currently working on implementing a dynamic add/remove child component feature in Angular. The parent component maintains a list of children and adds or removes them based on user selection. Adding a child works smoothly, but I encountered an iss ...

Encountered CORS error when attempting to access the dynamic menu API after logging

Currently, I am working on an Angular 6 and Codeigniter project. In this project, the slider and navigation menu bar are being fetched dynamically through a REST API. Everything runs smoothly until the login process, where a CORS error is encountered. htt ...

How can I clear the cache for GetStaticPaths in NextJs and remove a dynamic route?

This question may seem basic, but I can't seem to find the answer anywhere online. Currently, I am diving into NextJs (using TypeScript) and I have successfully set up a site with dynamic routes, SSR, and incremental regeneration deployed on Vercel. ...

Problem encountered when utilizing distributive conditional types in conjunction with a generic function

I've been working on creating a versatile function that takes an object T and a string property name of that object T. To guide me, I referred to https://www.typescriptlang.org/docs/handbook/advanced-types.html under the section: Distributive conditi ...

Encountering an npm issue: Clash in peer dependency between @angular/fire version 6.0.2 while trying to add angular/fire module

While trying to install the angular/fire module for Firebase authentication, I encountered a conflicting peer dependency error in the terminal. The error is related to upgrading an angular/compiler module from version 12.2.17 to version 12.0.0, which seems ...

Executing a ternary expression prior to confirming null values

Is it possible to shorten the code below using a ternary expression? if(paginator) { paginator.pageIndex = 1; } I attempted this: paginator.pageIndex = paginator ? 1 : undefined However, I am uncertain if this is the best approach or if there is a mo ...

Circular dependency detected between TransferHttpCacheModule, LocalizeRouterModule, and TranslateModule

I am in need of the following modules for my project: TranslateModule LocalizeRouterModule TransferHttpCacheModule This particular combination of modules seems to be causing a cyclic dependency issue. TranslateModule with TransferHttpCacheModule - works ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...

Android layout featuring Ionic2 navbar with icons aligned on both sides at the top

<ion-header> <ion-navbar align-title="center" color="primary" hideBackButton> <ion-buttons ion-button icon-only start class="card-buttons"> <button class="card-buttons" (t ...

Creating an array of objects in Angular 2

I'm facing an issue with the following expression: public mySentences:Array<string> = [ {id: 1, text: 'Sentence 1'}, {id: 2, text: 'Sentence 2'}, {id: 3, text: 'Sentence 3'}, {id: 4, text: 'Sen ...

Angular - How to fix the issue of Async pipe not updating the View after AfterViewInit emits a new value

I have a straightforward component that contains a BehaviorSubject. Within my template, I utilize the async pipe to display the most recent value from the BehaviorSubject. When the value is emitted during the OnInit lifecycle hook, the view updates correc ...

What is the most efficient approach to handle the next state after calling setState in react with immer?

Using Typescript, React, and Immer, I have set up a state management system to save profiles with multiple options. My goal is to ensure that the active profile has the correct option data before saving it. const { updateProfileList, getProfile } = useProf ...

Angular service providing components (TypeScript error)

This is my first time trying to dynamically inject components and so far, I've been successful. However, there's an error in Typescript that's bothering me (I don't like having errors in my code). If you want to check out the app, here ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

Designing a schema using mongoose and typescript

I have been attempting to create a new mongoose schema, but I keep encountering an issue where the new collection only contains two columns: _id and __v. None of the columns from my schema are included. Here is the code for the schema: import DataAccess f ...