Best Practices for Retrieving and Passing Data within a Resolver | Angular 10/11

Currently, I am working on fetching data into a component before it loads to customize some settings. However, I find the concept of resolver a bit confusing in terms of what it returns and how to interpret it.

I am struggling with getting the correct data types and understanding the proper way to call the fetch function to retrieve an Array that can be utilized in my component.

The Resolver snippet:

import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from "@angular/router";
import {Observable} from "rxjs";
import {Injectable} from "@angular/core";
import {EntryService} from "../app/entry.service";
import { Entrymodel } from "./entry.model";

@Injectable()
export class SinglePostResolver implements Resolve<any>{
 entries :Entrymodel[] = [];
  constructor(
    private entry:EntryService,
  ){

  }

  resolve(): Observable<any>//:Observable<EntryModel>{    
      return this.entry.getAventry()
  }

}

An example of the Entry model structure:

export class Entrymodel {
    id: string;
    surname: string;
    color: string;
    startDate: Startdate;
    endDate: Enddate;
    info: string;
    status?: string;
    inbet?: Inbetween[];
    editing?: boolean;
}

export class Startdate{
    day: string;
    month: string;
    year: string;
}

export class Enddate{
    day: string;
    month: string;
    year: string;
}

export class Inbetween{
    day: string;
    month: string;
    year: string;
}

The Fetch function:

  getAventry(){
    return this.firestore.collection('entry', x => x.where('status' , '==', 'Attending')).snapshotChanges();
  }

The goal is to reach this point:

ngOnInit(): void{
  this.route.data.subscribe( (data) => { 
   
  });
   console.log(this.entries)

  }

The assigned route configuration:

  { path: 'calendar', component: CalendarComponent, resolve: { singlePost: SinglePostResolver}}

My main confusion lies in correctly invoking the fetch within the resolver.

Should I subscribe or pipe? I am unsure about handling it and modifying the resolver's return value in the route. How do I convert that data into an accessible array?

I've attempted some ineffective approaches. While I have gone through the documentation on Observables and rxjs in Angular, I am finding it challenging to grasp the intricacies when dealing with Interfaces and Classes in conjunction with observables.

Answer №1

The data you will receive is expected to be of type

Observable<{ singlePost: any }>
based on the routing configuration. As long as ActivatedRoute is properly injected, there should not be any issues.

import { ActivatedRoute} from '@angular/router';

// ...

constructor(readonly route: ActivatedRoute) {}

ngOnInit(): void {
  (this.route.data as Observable<{ singlePost: any }>).subscribe((data) => { 
   console.log(data.singlePost);
  });
}

You may want to review the specific data being returned, as it's unclear to me. Consider specifying a type instead of using any for better clarity and understanding by yourself or others reading the code.

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

Is it possible to selectively exclude features such as routes and components from my Angular application during the build process based on the environment configuration file?

I am interested in creating two variations of my Application using the same codebase. One version will have the "registration" feature included, while the other will not. Is there a way to configure Angular so that an environment file dictates what is ex ...

Adding an object with a composite key to an IndexedDB object store is not permitted as the key already exists within the store. This limitation occurs when attempting to add an entry

I am facing an issue with my objectStore where adding an object with the same productId but a different shopName triggers an error in the transaction showing: ConstraintError: Key already exists in the object store.. This is how I initialized the objectSto ...

Encountering a surprise focus error in ngui-auto-complete within Angular

In the process of developing a web application, I have encountered an unexpected focus issue with the ngui-auto-complete on one of the pages. Despite not setting any focus event for this particular element, it remains focused once the content is initialize ...

Choose particular text within the editorState

I'm in the process of developing a sophisticated text editor utilizing draftjs. Take a look at this basic codesandbox to get a better understanding of the issue at hand. One of the challenges I'm facing is with a helper function called getCurren ...

A guide on integrating the URI.js library into an Angular2+ application

I'm currently exploring ways to integrate a third-party library called urijs into my Angular 2+ application. Below, you can see the relevant files involved in this process. // package.json { ... "dependencies": { ... "urijs": "^1.18.10", ...

Unlock the secrets of extracting video from a livestream and seamlessly transferring it to a local web server without the need

Hey there, I have this link: '' Although it's not a real link, entering it leads to a .m3u8 file for live video streaming. I attempted using this link in my Angular 6 app frontend, but encountered a cross-origin issue as the video is being ...

What is the best way to include 'SCSS' in the 'rollup' project that I have developed?

I am embarking on the creation of a React UI library and have chosen 'rollup' as my build tool. To enhance the project, I plan to incorporate TypeScript and utilize SCSS for styling. How can I implement SCSS within this setup? You can find the s ...

What type of observations can you make?

What is the correct way to specify the return type in the function getAll() instead of using any? getAll(): Observable<any> { return this.http .get<{ results: CharacterData[]; info: CharacterInfo; }>(characterUrl) .pipe(map((el) ...

Resolve the error message "variable is utilized prior to assignment"

Looking at the code snippet below, import { STS } from 'aws-sdk' const sts = new STS({ region: 'us-east-1' }); let accessKeyId: string let secretAccessKey: string sts.assumeRole(params, function(err, data) { if (err) { ...

express-validator not providing any feedback from endpoint when integrated with TypeScript

I've been working on validating the response body for my endpoint, but I'm running into an issue where I'm not getting a response from that endpoint when using express-validator. I'm confident that I have followed the official documenta ...

Dynamic user input using an enumeration

I am looking to develop a flexible input component (in React) that can dynamically generate different types of inputs based on the enum type provided along with relevant inputProps. The idea is to switch between different input components based on the type ...

Angular 4 - Issue with Top Navigation Bar not remaining fixed at the top of the page

I'm having trouble finding a solution to keep the top navigation bar fixed at the top of the screen without allowing it to scroll when the page becomes too long. I want to prevent the top nav bar from scrolling and maintain its position at the top of ...

Troubleshooting Angular2: SVG Disappearing Upon Page Reload with PathLocationStrategy

I encountered a strange problem with SVG while using Angular2's PathLocationStrategy. The SVG code in my HTML template looks like this: <svg class="bell__icon" viewBox="0 0 32 32"> <use xlink:href="#icon-notificationsmall"></use&g ...

Creating separate template reference variables for items in an *ngFor loop in Angular can be achieved by using the

I have a question about setting template reference variables for buttons with different attributes when rendering them using *ngFor in Angular. Specifically, I want to set the reference variable as #button1, #button2, and so on for each button, but also ne ...

Angular does not wait for the backend service call response in tap

Does anyone have a solution for subscribing to responses when the tap operator is used in a service? edit(status) { dataObj.val = status; // call post service with status.. this.service .update(dataObj) .pipe(takeUntil(this._n ...

Error encountered in Typescript function wrapper: The provided data type of number[] cannot be assigned to [number]

Within this code snippet, the function requires two arguments: one for the function that needs to be wrapped and another for the argument producer. function wrapper<K extends Array<any>, T>(fn: (...args: K) => T, pd: (...args: any) => K): ...

Error encountered: TypeScript module 'angularfire2/interfaces' not found in Ionic 3 with angularfire2-offline plugin

Encountering an error while trying to set up angularfire2-offline: [16:02:08] typescript: node_modules/angularfire2-offline/database/database.d.ts, line: 2 Cannot find module 'angularfire2/interfaces'. L1: import { Angula ...

Is it possible to apply filters to individual columns in a dynamic mat table using Angular?

Does anyone know how to add a filter for each dynamic column in an Angular Material table? I've only found solutions for static headers, but my table headers are constantly changing. I'm looking for something similar to this example: https://i.st ...

The program encountered an issue: TypeError - It is unable to access the property 'files' of an undefined value

Incorporating both ng2-file-upload and angular2-img-cropper into my Angular(2+) project has brought about a unique challenge. My goal is to utilize ng2-file-upload's Dropzone feature to load an image into angular2-img-cropper's cropping tool. Wh ...

Facing a 404 error when importing a 3rd party module into Angular 4+ due to the base tag

Currently, I am integrating Angular into my MVC application. To accomplish this, I have included a script tag in my layout view to reference the Angular source code, and so far everything is running smoothly. However, I encountered an obstacle when attemp ...