Improving observables in Angular after triggering a resolver

After successfully creating a Resolver in my code, I am wondering if there is a way to refactor my TypeScript component. Currently, whenever I try to remove any unnecessary parts of the code, it breaks my app. Here is the code for my resolver:

@Injectable()
export class MatchTableListResolver implements Resolve<MatchTable[]> {
    constructor(private readonly matchTablesService: MatchTablesService
                ) {}

    resolve(route: ActivatedRouteSnapshot, _state: RouterStateSnapshot): Observable<MatchTable[]> {
        console.log("inside resolver")
        return this.matchTablesService.list().map(data => {
            console.log("tata", data); return data});

    }
}

Now, I would like to refactor my component.TS file as follows:

this.urlWatcher$ = this.route.data.pipe(
        distinctUntilChanged(),
        withLatestFrom(this.matchTables$),
        map(([params, newMatchTables]) => {
            this.page = 1;
            this.startIndex = 0;
            this.endIndex = 50;

        const matchTableFromParam = newMatchTables.find(m => m.technicalName === params['id']);
        if (matchTableFromParam) {
            this.matchTableSelected = matchTableFromParam;
            this.selectLines(this.startIndex, this.endIndex);
        } else {
            if(newMatchTables.length > 0) {
                this.matchTableSelected = newMatchTables[0];
                this.router.navigate(['/configuration/matchtables/' + this.matchTableSelected.technicalName]);
                this.selectLines(this.startIndex, this.endIndex);
            }
        }
    })
);

this.matchTableList$ = this.matchTablesService.list().pipe(
    map(matchTables => {
        matchTables = matchTables.sort((a, b) => a.name.toLocaleLowerCase() === b.name.toLocaleLowerCase() ? 0 : a.name.toLocaleLowerCase() < b.name.toLocaleLowerCase() ? -1 : 1);
        this.matchTables$.next(matchTables);
    }),
    catchError( (error: HttpErrorResponse) => {
        this.loadingError$.next(true);
        return EMPTY;
    })
);

concat(this.matchTableList$, this.urlWatcher$).subscribe();

Since I am now using:

this.listMatchTable = this.route.snapshot.data.listMatchTable;

I am not very familiar with resolvers, but since I am receiving data from it, perhaps I can simplify things and potentially eliminate the observables. I'm unsure where to begin this process.

Answer №1

To retrieve data and parameters from a route, use the snapshot field.

this.id = this.route.snapshot.params['id'];
this.listMatchTable = this.route.snapshot.data.listMatchTable;

After that, you can proceed with your logic without using observables.

this.page = 1;
this.startIndex = 0;
this.endIndex = 50;

const matchTableFromParam = this.listMatchTable.find(m => m.technicalName === this.id);
 if (matchTableFromParam) {
   this.matchTableSelected = matchTableFromParam;
   this.selectLines(this.startIndex, this.endIndex);
 } else {
   if(newMatchTables.length > 0) {
     this.matchTableSelected = this.listMatchTable[0];
     this.router.navigate(['/configuration/matchtables/' + this.matchTableSelected.technicalName]);
     this.selectLines(this.startIndex, this.endIndex);
   }
 }

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 disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

Gain a comprehensive understanding of the JavaScript syntax utilized throughout the code

I stumbled upon this JavaScript code that enables asynchronous file uploads, but there are certain parts of it that I'm struggling to grasp. Any insights or explanations would be greatly appreciated - many thanks in advance. // Utilizing Ajax for Fil ...

Executing function from component within Cypress test

I have an Angular 7 application and I am using Cypress to test some canvas/map components. One of my requirements is to call a function within a component to verify the geojson being displayed on the map. When I do this in Chrome by calling ng.probe($0).c ...

Inquiries prior to projecting rays

As I delve into the world of Interaction with Three.js, several questions arise in my mind. 1) Can you shed some light on what exactly Viewport Coordinates are? 2) In what ways do they differ from client Coordinates? 3) How did we come up with this form ...

Loading data synchronously in Angular6 routes

After recently integrating Server-Side Rendering (SSR) into my Angular6 application to render dynamic HTML in a crawlable manner, everything appears to be functioning properly. But I am facing an issue when trying to render data from an API endpoint. Upon ...

How can I temporarily change an image when clicking on it using JavaScript?

I am working on an image section where I want to change the image for a few seconds when clicked and then revert back to the original image. Here is the code I have tried: <img src="contacticons.jpg" usemap="#image-map" id="imgName"> <a onclick ...

How to implement loading an external script upon a page component being loaded in NextJS

I recently transferred an outdated website to Nextjs and I am having trouble getting the scripts to load consistently every time a page component is loaded. When navigating between pages using next/link component, the scripts only run the first time the ...

Prevent the display of list elements upon clicking by utilizing Angular's Observable and async features

My search bar allows users to enter characters, and through Angular Observable with HTTP GET, they receive suggestions for similar keywords. When a user clicks on a suggestion, it populates the search form with that keyword. The issue is that even after s ...

Tips for constructing a multi-dimensional entity from an existing object?

Looking to frame an object as a two-dimensional entity. let data = [ {'id':1, 'price':'12', 'price_type':'abc', 'mode':1, 'year':1}, {'id':1, 'pri ...

Guide on incorporating reusable component inputs in Vue 3

Does anyone have any tips on creating reusable component input in Vue 3? Similar to how it's done in React: For example, Using <Input /> as a reusable component in the parent component import { ref } from 'vue'; import Input from &a ...

Launching a peek inside a modal using AngularJS through a service

Feeling a bit unsure about my approach... I'm diving into my first AngularJS app and trying to grasp the architecture. So, I've built a service called isAjax, utilizing the $http module to handle API calls for me. I'm capturing the succes ...

Error occurs when trying to create or delete a folder in Express.js

Implement Folder Creation Code in index.js let companydir = './views/campaigns/' + companyname; if(!fs.existsSync(companydir, { recursive: true })) { fs.mkdirSync(companydir, { recursive: true }); } var dir = companydir + &apo ...

Press the "Reveal More" button to expand the content to its full size

I am currently working on coding a "read more" section using a button. I have looked at some existing solutions, but none of them are to my liking. My plan is to create a div that includes all the relevant content. My goal is to have a div at the bottom w ...

An error was encountered stating "TypeError: Unable to call function on undefined object while attempting to utilize a JSON object

My current setup involves using D3js with MongoDB and AngularJS to showcase my data. Everything works smoothly until I decide to give my JSON array a name. Suddenly, Angular starts throwing errors at me and I'm left confused as to why. Here is the or ...

Retrieving JSON information using dynamic routes in Next.js

I am working with a json file that contains content for various pages categorized under "service". In my nextJS project, I utilize dynamic routes with a file named "[serviceId].tsx" for routing. This setup is functioning correctly. However, I am facing an ...

Using vuetify's v-autocomplete component with the options to select all and clear items

I am trying to incorporate a "Filter by values" feature in my application similar to Excel or spreadsheets. However, I am facing difficulty with implementing the 'Select all' and 'Clear' button in v-autocomplete. <v-col> < ...

Instead of receiving my custom JSON error message, Express is showing the server's default HTML error page when returning errors

I have set up a REST api on an Express server, with a React app for the front-end. The design includes sending JSON to the front-end in case of errors, which can be used to display error messages such as modals on the client side. Below is an example from ...

What is the process for performing a redirection in Node JS?

I have been working on a task to redirect a page to the home page with the route '/search' upon form submission. Within my submit.html file, there is a form that utilizes the '/submit' post method to submit the form data when the submit ...

Tips for troubleshooting issues with the Angular CLI development server

When I run ng serve from the Angular CLI in development, I expect my application to be served locally with live reloading. Usually, I see a single [WDS] Live Reloading enabled. message in the console after loading my app in the browser. Issue at Hand: La ...

When attempting to send a request for the JSON body to Node.js using the await fetch method, I encountered an issue

Recently, I started working with node js and attempted to fetch JSON data using the code below: const req = await fetch( "http://localhost:3000/api/auth/signin", { method: "POST", header:{ 'Accept':&apo ...