Managing the deactivation of two observables

When implementing my canDeactivate() route guard, I encounter an issue with calling a modal that contains two buttons: ok and cancel. The goal is to return true when the user clicks the ok button to allow them to leave the page, and false when the cancel button is clicked. Below is the current code snippet:

canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    let can =  component.canDeactivate();
    //let result = new Observable<boolean>();
    let okResult = new Observable<boolean>();
    let cancelResult = new Observable<boolean>();

    if (!can) {
      component.myChangesModal.show('Warning', 'You are about to leave this page with unsaved changes.');

      okResult = component.myChangesModal.okEvent.map(() => true);
      //okResult.subscribe();

      cancelResult = component.myChangesModal.cancelEvent.map(() => false);
      //cancelResult.subscribe();
      console.log(okResult);
      console.log(cancelResult);

      const observablesArray = [okResult, cancelResult];

      let result = Observable.combineLatest.apply(this, observablesArray).take(1);
      result.subscribe();

      return result;
    }
    return true;
  }

Initially, I had a simpler implementation where only one observable was used to monitor clicks on the ok button and it worked flawlessly for that single action. However, when attempting to expand it to work with multiple buttons, such as the cancel button, issues arose. Here is the original code snippet that functioned perfectly for a single button:

canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    let can =  component.canDeactivate();
    let result = new Observable<boolean>();

    if (!can) {
      component.myChangesModal.show('Warning', 'You are about to leave this page with unsaved changes.');

      result = component.myChangesModal.okEvent.map(() => true);
      result.subscribe();

      return result;
    }
    return true;
  }

I seek guidance on what mistakes I might be making in trying to incorporate multiple observables into my canDeactivate modal, and how to rectify the problem.

Answer №1

CombineLatest will only proceed once both observables have emitted a value, which isn't possible in your scenario. Instead, you should use Observable.merge.

return okResult.merge(cancelResult).take(1)

or

return Observable.merge(okResult, cancelResult).take(1)

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

Updating the log file location for electron-log in an Angular application integrated with Electron

I am currently developing a project using Angular 6 integrated with Electron. I have managed to successfully incorporate the electron-log library using ngx-electron. As a result, my application is functioning well and logging data to the default path: C:&b ...

.Net Core receives the method name instead of the parameter value passed by TypeScript

Can someone explain why the code is passing "getFullReport" as the eventId instead of the actual value while making its way to the .Net Core 3.1 side? Prior to the call, I double-checked with a console.log to ensure that eventId holds the correct ID I am ...

Leveraging gulp to enhance the module namespace in the TypeScript output of various files

I faced an issue when using the methodology of one file - one class in a TypeScript project, as shown in the example below. File Greeter.ts module App { export class Greeter { constructor(public greeting: string) { } public greet() { ...

Best practices for safely handling dynamic keys in Typescript

I am searching for a secure method to create keyed objects in this manner: interface Types { RED: 'RED'; BLUE: 'BLUE'; GREEN: 'GREEN'; } type TypeKeys = keyof Types; const COLORS: Types = { RED: 'RED', B ...

What is the best way to populate a textbox with values depending on the selection made in a combobox using

I have a combobox that should automatically populate the textboxes when an option is selected. The combobox, named Aircraft type, is connected to the textboxes 'number of motors' and 'MTOW', as well as the combobox 'Type of Motor&a ...

Unable to send a function as props to a child component in TypeScript

Within my application, I have a parent component that holds a state and a setState function. This state and function are then passed down to a child component in order to retrieve values (such as input field data). When the function is triggered in the chi ...

The issue at hand in Ionic 2 / Angular 2 is that the NPM module is being utilized as a value instead of referring to a type

I'm currently working on integrating the npm module "ajv" into my Ionic 2 (Angular 2) project. You can find more information about this module at . After running "npm install ajv --save", I proceeded to make some modifications to my app.modules.js fi ...

What is the method for determining the length of a piped array within a template?

Here is a sample code snippet showcasing how to get the length of an array when not using a pipe: <my-component [arrLen]='arrayA.length'></my-component> But what if you want to get the length of a filtered array using a pipe? The exa ...

Angular: Modify the spelling of a single term across an application to cater to international audiences

I am working on an Angular application that must support both British and American English languages. The language setting is determined by a server at start-up, allowing me to know which language to display. One specific change I need to make throughout ...

Revising Global Variables and States in React

Recently delving into React and tackling a project. I find myself needing to manage a counter as a global variable and modify its value within a component. I initialized this counter using the useState hook as const [currentMaxRow, setRow] = useState(3) ...

Getting started with creating a dynamically changing table with just 2 initial rows is easier than you

My challenge is to dynamically create rows in a table, but I am unsure how to start the table with two rows on the onInit event. To get an idea of how the table operates, you can view it here: Visit stackblitz ...

The Angular 2 view appears on the screen before the data finishes loading in the ngOnInit

Utilizing the github API in my angular 2 application, I encounter an issue where the view renders before ngOnInit has finished loading data. This leads to a Cannot read property of undefined error. The relevant portion of my code is as follows: ngOnInit() ...

The OnPrepareResponse method in StaticFileOptions does not trigger when serving the index.html file

Currently, I am attempting to disable caching for index.html in my Angular SPA that is connected to a .NET Core 2.2 backend. I am following the instructions provided in this particular answer by implementing an OnPrepareResponse action for my StaticFileOp ...

The Ionic project compilation was unsuccessful

Issue: This module is defined using 'export =', and can only be utilized with a default import if the 'allowSyntheticDefaultImports' flag is enabled. Error found in the file: 1 import FormData from "form-data"; ~~~~~~~~ node ...

Encountered Typescript errors TS1110 and TS1005

Error in TypeScript: typings/node/node.d.ts(83,23): Type expected. TypeScript issue: typings/node/node.d.ts(1830,52): Expected '=' sign. My TypeScript compilation is failing at node.d.ts, despite multiple attempts to reinstall it. ...

Combining rxjs events with Nestjs Saga CQRS

I am currently utilizing cqrs with nestjs Within my setup, I have a saga that essentially consists of rxjs implementations @Saga() updateEvent = (events$: Observable<any>): Observable<ICommand> => { return events$.pipe( ofType(Upd ...

The Angular service worker is running in a secure SAFE_MODE environment

My Angular PWA had a perfectly functioning service worker until I made the upgrade from Angular 5.0 to 7.2. After the upgrade, I encountered the following error in /ngsw/state Driver state: SAFE_MODE (Initialization failed due to error: Invariant violate ...

Tips for selecting the correct type for an array of Unions with the help of Array.prototype.find

I have the following variations: type First = { kind: 'First', name: string } type Second = { kind: 'Second', title: string } type Combo = First | Second; I am attempting to locate the element of type First in a Combo[], as shown bel ...

Select the location for rendering the application within the root HTML using Single-SPA

I am strategizing to utilize the single-SPA framework alongside angular in order to construct a microfrontend architecture for a website. The current setup of the website is based on a legacy monolith structure, but we are aiming to transition it into a mi ...

Ensure the inferred type is asserted in TypeScript

Is there a more elegant approach to assert the type TypeScript inferred for a specific variable? Currently, I am using the following method: function assertType<T>(value: T) { /* no op */ } assertType<SomeType>(someValue); This technique prov ...