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

Testing TaskEither from fp-ts using jest: A comprehensive guide

Entering the world of fp-ts, I encounter a function (path: string) => TaskEither<Erorr, T> that reads and parses configuration data. Now, my challenge is to create a test for this process. Here is what I have tried so far: test('Read config& ...

Creating a custom button for exporting a high chart to CSV

My Angular project involves exporting a chart to various formats, such as png, jpeg, pdf, and SVG. However, I am encountering an issue when trying to export the chart as CSV or . I have attempted the following code: this.lineChart.chart.downloadCSV(); //F ...

Navigating with the router on a different page

My appcomponent contains all the routes, and on the next page I have several links that are supposed to route to the same router outlet. How can I navigate when a link is clicked? I attempted using [routerLink]="['PersonInvolved']", but I encoun ...

Strategies for Dealing with 'No Search Results' in Your Search Functionality

I am currently facing an issue with displaying "No Results Found" when a user utilizes my search feature. The current problem is that "No Results Found" appears immediately on the screen and then disappears while a search query is being processed, only to ...

Send the latest cell parameters from the CellRendererFramework element to the main grid component

Within ag-grid, I am utilizing the cellRendererFramework to render a specific cell. By accessing the params property, I can retrieve the values of the cell from the parent grid component. However, I now have the need to update these params from my cellRend ...

Unable to display animation without first launching it on Rive web

I attempted to incorporate a Rive animation into my Angular web application <canvas riv="checkmark_icon" width="500" height="500"> <riv-animation name="idle" [play]="animate" (load)=&qu ...

Synchronizing data between parent and child components using two-way binding with emit in Vue 3 using TypeScript

Within my code, there is a child component: <template> <label :class="className + ' ctrl'"> <span><LocCtrl :page="pageName" :locKey="labelLoc" /></span> <input type=&q ...

Enhance TypeScript class declarations with additional properties

Our company has developed its own test framework for our software because we found it difficult to use an open-source framework within the context of our specific development needs. Recently, I took on the task of creating Typescript Definition Files to e ...

Exploring the capabilities of supertest by testing endpoints in Express with NodeJS

Having trouble setting up a test environment to test my TypeScript Express Node.js endpoints. Here are the packages I've installed: jest ts-jest jest-junit supertest @types/supertest @types/jest This is how my spec file looks like: imp ...

Ways to automatically display the Nebular Accordion using NgFor

Struggling with the latest Nebular version in Angular 7, I'm encountering a problem when using the nebular accordion component. Problem: The default behavior should have only one accordion expanded at a time, but setting expanded = true expands all of ...

Error: The file or directory specified at ' ode_modules@fullcalendarcommon' does not exist

While attempting to build or serve my Angular project, I encountered the following error: 'An unhandled exception occurred: ENOENT: no such file or directory, lstat '\node_modules@fullcalendar\common' See "\AppData\ ...

Error Message: Fatal error encountered - TS6046: The value provided for the '--moduleResolution' option is invalid. Valid options include: 'node', 'classic', 'node16', 'nodenext

As I develop a next.js web app with typescript and tailwind CSS, I encountered an issue. When running yarn dev in the terminal, I received this error message: FatalError: error TS6046: Argument for '--moduleResolution' option must be: 'node ...

Ionic 4 ion-button unable to reflect changes in ngStyle when Variable value is modified

In my Ionic 4 project, I have a page where clicking on a button changes a variable value and updates the ngStyle. There are two buttons, "Friends" and "Families", each meant to have a different background color when selected. Initially, the Friends butto ...

Issue with Angular Material date picker: Date Parsing UTC causing dates to display as one day earlier

After exploring numerous threads related to this issue and spending several days trying to find a solution, I may have stumbled upon a potential fix. However, the workaround feels too messy for my liking. Similar to other users, I am encountering an issue ...

Is there a way to customize the default styles of Kendo UI for Angular?

Is it possible to customize the default datepicker styles to look like the design in the second image? https://i.sstatic.net/h8yfA.png https://i.sstatic.net/PfiSf.png ...

Angular chat integration

In my application, I have a parent component called "chat" with two child components - "sidebar" (which displays the user list) and "conversation detail" (which shows the chat with each user). The functionality I am aiming for is that when a user is clicke ...

Having Trouble with Angular 6 Subject Subscription

I have created an HTTP interceptor in Angular that emits a 'string' when a request starts and ends: @Injectable({ providedIn: 'root' }) export class LoadingIndicatorService implements HttpInterceptor { private loadingIndicatorSour ...

The importance of handling undefined values in TypeScript and React

There is a condition under which the IconButton element is displayed: {value.content && <IconButton aria-label="copy" onClick={() => copyContent(value.content)}> <ContentCopy /> </IconButton> } However, a ...

Tips for Structuring Code in a Resource Management Phaser Typescript Project

I'm currently developing a resource-management game and require a "collection manager" to streamline interactions between states and objects in Typescript. Let's imagine the game revolves around nurturing cats. In one state, players advance time ...

Retrieve the additional navigation information using Angular's `getCurrentNavigation()

I need to pass data along with the route from one component to another and retrieve it in the other component's constructor: Passing data: this.router.navigate(['/coaches/list'], { state: { updateMessage: this.processMessage }, ...