What is the best way to ensure that the base class Resolver finishes before allowing the derived class Resolver to execute?

I have a situation where many of my resolvers (@angular/router Resolve) need to query the same data before executing their route-specific queries. To streamline this process, I want to create a resolver base class that resolves the initial data before the resolve() function in the derived class is triggered.

The base class:

export class MyBaseResolver implements Resolve<Observable<string>> {
      
        myBaseProperty: string;

        constructor(service: MyService) {}
        
        resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): string {
    
            this.service.getData()
                .subscribe((data) => {
                    this.myBaseProperty = data;
            });
        
        }
}

The derived class:

export class MyDerivedResolver implements Resolve<Observable<Thing>> extends MyResolverParent {

        constructor(public service: MyService) {
            super(service);
        }
        
        // How can I modify this to ensure it waits for MyBaseResolver.resolve() to finish 
        // so "myBaseProperty" is ready to use?
        resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Thing> {
    
            return this.service.getOtherData(myBaseProperty);
        
        }
}

What is the best approach to make MyDerivedResolver wait for MyBaseResolver.resolve() to complete, ensuring that myBaseProperty is available and valid?

Answer №1

class CustomDerivedResolver extends AdvancedResolver<Observable<Item>> implements ParentResolver {

        constructor(public dataService: DataService) {
            super(dataService);
        }
        
        // How can we ensure that MyBaseResolver.resolve() finishes executing 
        // before accessing "myBaseProperty"?
        resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Item> {
            
            return super.resolve(route, state).pipe(mergeMap(()=>this.dataService.fetchAdditionalData(myBaseProperty)));
        
        }
}

I'm not entirely sure why you're trying to call this.service.getData() from the base class.

Answer №2

Although untested, this is the strategy I would employ

export class NewResolver implements Resolve<Observable<string>> {
      
        myNewProperty: string;

        constructor(service: NewService) {}
        
        async resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): string {
    
            const information = await this.service.getInformation().toPromise();
            this.myNewProperty = information;
            return information;
        
        }
}

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

Issue with React filter function where data is not being displayed when search query is left

I am facing an issue where the data does not show up when the search term is empty. Previously, I used to have this line in my code if (!searchTerm) return data for my old JSON data, and it worked fine. However, now that I'm using Sanity CDN, this lo ...

I am experiencing issues with my Jest unit test case for Material UI's multi select component failing

I've been working on writing a unit test case for the material UI multi select component. The code for the parent component is as follows: import {myData} from '../constant'; export const Parent = () => { const onChangeStatus= (sel ...

Using JQuery within Angular 4 is a valuable tool for enhancing the functionality

As a newcomer to Angular, I am experimenting with using jQuery alongside Angular 4. In my search for information, I stumbled upon this question on Stack Overflow. Inside the question, there was an example provided that can be found here. However, when att ...

Utilizing React-hook-Form to transfer data between two SelectBoxes

This simple logic is causing me some trouble. Despite using react-hook-form, I thought this would be easy. However, after struggling with it for over a week, I'm still facing challenges. I'm incorporating nextUI components into my project. < ...

Exploring TypeScript reflections within a specific namespace

(Building upon previous discussions about dynamically loading a TypeScript class) If I am currently within a namespace, is there a method to reference classes within the namespace in order to utilize 'reflection' to invoke their constructors? n ...

Customizing the Global Error Handler in Angular

Our project utilizes a global error handler to manage errors. However, we have encountered a unique scenario where we need to handle a specific case separately but are unable to do so. The global error handler is configured in the app.module.ts: { provide: ...

Creating a type-safe method wrapper in TypeScript based on function names

Many Q&As discuss creating a function wrapper in TypeScript, but my question is how to do the same with named methods. I am interested in writing something similar to this JavaScript code: function wrap(API, fnName, fn) { const origFn = API.p ...

Utilizing the power of KendoUI and Angular2 for autocomplete: governing accepted values

I successfully integrated the KendoUI Autocomplete feature with live search functionality. It is working well and meeting my expectations. However, I want to limit the autocomplete suggestions to values from the list only. For example, if I type "London" ...

Ionic app encountering issues with Facebook OAuth login functionality

Currently, I am implementing Facebook Auth for my Ionic app by using the Firebase module. Despite setting up the firebase module correctly initially, I keep encountering an error during the login process. It should be noted that the login function worked p ...

Component's mocking service is being ignored

I am currently exploring how to simulate a service (specifically one that makes http calls) in order to test a component. @Component({ selector: 'ub-funding-plan', templateUrl: './funding-plan.component.html', styleUrls: ['. ...

The VSCode's intellisense for Angular Material fails to function effectively

In the midst of my project on Angular version 13, I have successfully installed Angular Material using the command below: ng add @angular/material The package has been properly included in the node_modules folder. However, when working with TypeScript ...

Issue encountered when attempting to save items in the browser's local storage

I'm encountering an issue: ERROR Error: Uncaught (in promise): DataCloneError: Failed to execute 'put' on 'IDBObjectStore': Position object could not be cloned. Error: Failed to execute 'put' on 'IDBObjectStore& ...

Issue with Next.js: Router.push not causing page to refresh

I'm currently developing a next.js page called /page/data/[dataId] (this page is accessed when a user clicks on a link from the page /page/data, where I fetch the list of items through an API). When a user clicks on a button, I make an API call to de ...

unable to assign an array to a different array in typescript

I'm facing an issue with assigning values to the private kitems array in my class. Despite defining it as kitems:any[], when I try to assign a value using this.kitems = items; and then log this.kitems, it shows up as an empty array. createprofile() { ...

Problem encountered while directing to a component within Angular

Here is the overview of my directory structure: Directory Structure login.component.ts: import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms ...

The function '() => Promise<T>' cannot be assigned to type 'Promise<T>'

Here is an interface I have: export interface ITreeViewItem { getChildren: Promise<ITreeViewItem[]>; ... Now, let's take a look at the implementation of it: export class MyClass implements ITreeViewItem { public async getChildren() ...

Angular - Set value on formArrayName

I'm currently working on a form that contains an array of strings. Every time I try to add a new element to the list, I encounter an issue when using setValue to set values in the array. The following error is displayed: <button (click)="addNewCom ...

Error: Observable<any> cannot be converted to type Observable<number> due to a piping issue

What causes the type error to be thrown when using interval(500) in the code snippet below? const source = timer(0, 5000); const example = source.pipe(switchMap(() => interval(500))); const subscribe = example.subscribe(val => console.log(val)); V ...

Using an asynchronous pipe filter with the ngFor loop in Angular 2 for efficient data

I have a JSON array that I need to iterate through in order to display data using an NGfor Loop. My goal is to apply filters after the data has been loaded to refine the results. The issue I am facing is that my pipe filter is returning 'cannot read p ...

Obtain accurate dispatch type by leveraging ConnectedProps in conjunction with redux-thunk

Currently, I am utilizing Redux-Toolkit and Typescript. Specifically, my goal is to implement ConnectedProps as recommended in the redux documentation. However, it appears that the dispatch type is not recognized correctly (it is identified as a normal Dis ...