Using the ngrx signalStore within the facade design pattern - a step-by-step guide

How can I utilize ngrx's new signalStore in Angular to fetch locations of arms, save them in the state, and replace a service with LOCATION_STORE after setting the locations on a map with markers? The challenge lies in waiting for the response of locations before making the switch.

export const LOCATION_STORE = signalStore(
  { providedIn: "root" },
  withState(() => inject(LOCATION_STORE_INITIAL_STATE)),
  withMethods((store, atmService: AtmsService = inject(AtmsService)) => ({
    fetchLocations: rxMethod<void>(pipe(
      debounceTime(300),
      distinctUntilChanged(),
      tap(() => patchState(store, { loading: true })),
      mergeMap(() => atmService.getBranchesAndAtms().pipe(
        tapResponse({
          next: (locations: Array<LocationModel>) => {
            const branches: Array<LocationModel> = locations.filter((res: LocationModel) => res.isBranch);
            const atms: Array<LocationModel> = locations.filter((res: LocationModel) => !res.isBranch);
            return patchState(store, { atms, branches })
          },
          error: (errorCode: string) => patchState(store, { error: errorCode }),
          finalize: () => patchState(store, { loading: false })
        })
      ))
    )),
  }))
)

# Implementation using Google Maps library 

 initiateMap(mapContainer: HTMLElement) {
    return forkJoin([ this.getGoogleMap(mapContainer), this._atmService.getBranchesAndAtms() ]).pipe(
      tap(([ googleMap, locations ]): void => {
        const markers: Array<google.maps.Marker> = this.addMarkers(locations);
        this.addMarkerClusterer(googleMap, markers);
      })
    )
  }

Answer №1

To effectively manage state in your application, consider implementing a store with entities. Check out this insightful article on Medium for more information: Click here

Instead of relying on AtmsService, retrieve data from the store. Reserve the use of AtmsService solely within the store provider, which can be named AtmsStore.

Your initiateMap() function should be structured like so:

private atmsStore = inject(AtmsStore);

initiateMap(mapContainer: HTMLElement) {
   return this.getGoogleMap(mapCOntainer).pipe(
      tap(googleMap => {
         const markers: Array<google.maps.Marker> = this.addMarkers(this.atmsStore.entities());
         this.addMarkerClusterer(googleMap, markers);
      })
   )
}

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

Combining and Reorganizing JSON Data with Arrays of Objects

Seeking assistance after spending a considerable amount of time on this task. Our objective is to dynamically merge two JSON responses by utilizing the data from JSON Data 2 (prodsub_id) with JSON Data 1 (id). Refer to the sample JSON data below. JSON Dat ...

The Kendo Date Picker is failing to update properly when the k-ng-model is modified

I am facing an issue with my code involving two date pickers and one dropdown list. I want the date pickers to change based on the selected item from the dropdown list. Here is the relevant portion of my code: $scope.toolbarOptions = { i ...

Convert a JSON object into a new format with a nested hierarchy

The JSON object below is currently formatted as follows: { "id": "jsonid", "attributes": { "personName": { "id": "name1", "group": "1.1" }, "ag ...

Is there a way to retrieve cookie data from a component that has been rendered in _app.js using Next.js?

Within my next.js application, I have implemented a functionality where a hashed token from an OAuth2 provider is stored using cookies. Once the user completes the necessary steps, they are logged in and the cookie storing the token is set. The log in but ...

Unable to apply nativeElement.style.width property within ngOnChanges lifecycle method

My current task involves adjusting the width of containers while also monitoring changes in my @Input since the DOM structure is dependent on it. @Input('connections') public connections = []; @ViewChildren('containers', { read: Elemen ...

Angular7 is throwing an error saying it cannot read the property 'post' of undefined

Looking to create a custom validation in Angular 7. Here is the code snippet: CheckUserNameExisit(control: AbstractControl): { [key: string]: any } { console.log('in functions') return new Promise(resolve => { let httpClient: HttpClient ...

Getting data from a latin1 (iso-8859-1) database using javascript/nodejs: Tips and Tricks

My ancient mysql database (mysql 5.0.2) is in latin1 format and I'm encountering an issue with getting data from it. Non-ascii characters such as Â, À, and Á are appearing as 'ef bf bd' in hex, which means different characters are being d ...

What could be causing my Next.js page to produce static files containing outdated data while being built?

Currently, I'm tackling a Next.js project where I utilize Prisma to fetch grades from a database located in the app directory. These fetched grades are then displayed using a component called GradesComponent. However, whenever I execute npm run build, ...

Can a universal Save File As button be created for all web browsers?

Currently, I am in the process of developing a music player on the client side and I am seeking a method to save playlists that include mp3 data. Concerns with localStorage The restriction of a 5mb limit for localStorage makes it impractical for my needs. ...

Custom Native Scrollbar

Currently, there are jQuery plugins available that can transform a system's default scroll bar to resemble the iOS scroll bar. Examples of such plugins include . However, the example code for these plugins typically requires a fixed height in order to ...

expand the module's children routes by including additional options from another module

Imagine we have a module called "Parent" which has some child routes: const routes: Routes = [ { path: '', component: ParentComponent, children: [ { path: '/:id', ...

Guide to creating a reminder feature in NestJS

In my NestJS project, I've created a POST API to add a Date object representing the date and time for sending notifications to a mobile app. Currently, I am working on checking which reminders have been reached for all users in order to trigger remin ...

Issue with $_POST['projectSubmit'] not functioning as expected

I'm having trouble with echoing a JavaScript script after hitting the submit button. Instead of working, it just closes the modal and refreshes the page. I tried using `if($_POST['projectSubmit'])` instead of enclosing it in `isset()`, but i ...

Unable to import library in Angular framework

I'm currently in the process of setting up js-beautify, which can be found at https://www.npmjs.com/package/js-beautify I installed it using the command npm install js-beautify --save Next, I added the import to my app.component.ts file The documen ...

Using AngularJS: The ultimate guide to invoking a service within a module

I have a controller that successfully calls a service. However, I now need to access a method within that service from another module. How can I achieve this? BaSiderbarService: (function() { 'use strict'; angular.module('BlurAdmi ...

Setting the selected option of a select form element dynamically in Vue 3

Is there a way to dynamically set the selected option in Vue 3 when the data value doesn't match any available option value? Situation: If Florida (FL) is the stored state value and the country changes from United States (US) to Canada (CA), the Sta ...

Troubleshooting: WordPress failing to launch Bootstrap Modal

I recently transformed my PHP website into a WordPress theme, but unfortunately, I am facing an issue with my Bootstrap modal not opening in WordPress. ***Header.php*** <a id="modal_trigger" href="#modal" class="sign-in-up"><i class="fa fa-user ...

The OrbitControls feature in Three.js seems to be malfunctioning

When I try to execute the script, an error message appears in the console saying "THREE.OrbitControls is not a constructor". https://i.sstatic.net/H5ap3.png What am I doing wrong? The code I used was taken from a manual. var controls; controls = new ...

prevent unauthorized changes to input using browser developer tools in Angular

We have a login page for our application with three fields: "user name," "password," and a "login" button. Here's the issue I'm facing: I enter a valid user name. Then, I open the Browser Developer Tools and input the following code: d ...

Why doesn't Typescript 5.0.3 throw an error for incompatible generic parameters in these types?

------------- Prompt and background (Not crucial for understanding the question)---------------- In my TypeScript application, I work with objects that have references to other objects. These references can be either filled or empty, as illustrated below: ...