RXJS - Hold off until the shop is fully stocked

Here's a function I have that needs some adjustment:

combineLatest([this.contact$, this.account$]).pipe(
  map((res) => {contacts = res[0], account = res[1]})).subscribe()

I am facing an issue where the contact$ selector is sometimes empty. If it is empty, I need to call a service to populate the store. I attempted a fix as shown below, but it does not work as intended. Here is an example of what I want to achieve:

combineLatest([this.contact$, this.account$]).pipe(
  map((res) => {
    if(res[0].length === 0) {
      this.getContacts()
    }
    contacts = res[0];
    account = res[1]}
  ).subscribe()


getContacts() {
  this.myService.getContacts().subscribe(res => {
     this.store.dispatch(myAction.addContacts({contacts: res}))
  })
}

Answer №1

Interesting query, for which I have yet to discover a solution free of any unpleasant odors. Nevertheless, one possible approach is as follows:

  • Begin by subscribing to your observable
  • Implement a timeout (perhaps 50ms) to fetch data if none exists in the store after the set period
this.timer$.subscribe( (..) => {
    this.fetchData();
});

this.data$.subscribe( (..) => {
    this.unsubscribeTimer();
    this.handleData();
});

Answer №2

When working on my projects, I often use this method where I invoke the selector:

this.products$ = this.store.select(getProducts).pipe(
  tap(x => {
    if (x.length === 0) {
      this.store.dispatch(ProductActions.loadProducts());
    }
  }),
  // Filtering out an empty array to prevent emission to combineLatest
  filter(x => x.length > 0)
);

Utilizing Selectors

export const getProducts = createSelector(
  getProductFeatureState,
  state => state.products
);

To access the complete codebase, visit:https://github.com/DeborahK/Angular-NgRx-GettingStarted/tree/master/APM-Demo4

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

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

In this guide, we will explore the process of designing unique styles for ng

What is the proper way to customize CSS for a specific element? &.ng-select-focused { &:not(.ng-select-opened) > .ng-select-container { border-color: $ng-select-highlight; box-shadow: $ng-select-box-shadow; } } The offi ...

Guiding you through the process of dynamically defining a port in proxy.conf.json or proxy.conf.js

Starting my Angular4 application for development involves running npm run start, where start is defined as "start": "ng serve --proxy=proxy.conf.json". Within the proxy.conf.json file, I have: { "/api/**": { "target": "http://localhost:80 ...

Encountering error codes TS1005 and TS1109 while trying to run an Angular 6 project

Having difficulty starting my Angular 6 app due to this specific error. Is there a solution available? ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected. node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ...

Moment-Timezone defaults to the locale settings after the global Moment locale has been established

I am currently developing an application using Typescript that requires features from both Moment.js and moment-timezone. To localize the date and timestamps within the application, I have set moment's locale in the main app.ts file to match the langu ...

The issue of returning a boolean value in an rxjs function leading to failure

Hey there, I am currently learning about rxjs and I want to create an observable that returns either true or false. This is my attempted code: checkLoggedIn(): Observable<boolean> { // Check with the server if the user is logged in if(this._tok ...

Encountering an error in resolving symbol values statically within the Angular module

Following a helpful guide, I have created the module below: @NgModule({ // ... }) export class MatchMediaModule { private static forRootHasAlreadyBeenCalled: boolean = false; // This method ensures that the providers of the feature module ar ...

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

ngIf failing to pick up on variable updates

Utilizing the greensock animation library to animate various components has presented a problem during the variable update within the onComplete function linked to a *ngIf. Strangely, Angular fails to recognize the variable update within the callback. Des ...

Error message: Angular material StaticInjectorError - MatDialog provider not found

After trying to launch my Angular 5 page in the browser, I encountered an error message in the console. ERROR Error: StaticInjectorError(AppModule)[AppComponent -> MatDialog]: StaticInjectorError(Platform: core)[AppComponent -> MatDialog]: ...

Send all Apache requests within a specified URL directory to a particular file, while directing all other requests to a different file

I am in the process of setting up an Angular application along with a basic PHP CRUD API backend on my Raspberry Pi 3 using Apache. My goal is to configure the mod_rewrite rules to first check for existing files or directories, then redirect requests for t ...

How can one determine the data type by analyzing the key value?

I'm attempting to determine the return type of getAllRaces() as () => Race[]. Here is what I have tried so far: type CollectionMap = { races: Race[] horses: Horse[] } type Race = { date: Date } type Horse = { name: string } typ ...

What can be done to fix the issue of a missing value accessor for a form control name in Angular

I am on a mission to wrap <app-test-field> components within the confines of the <form> tag, where I can dynamically bind in formControlName and formGroup to TestField input using Angular with StorybookJS. Alas, I have stumbled upon the follow ...

Commitments, the Angular2 framework, and boundary

My Angular2 component is trying to obtain an ID from another service that returns a promise. To ensure that I receive the data before proceeding, I must await the Promise. Here's a snippet of what the component code looks like: export class AddTodoCo ...

uninstall angular cli from all environments

Hey there! I've attempted to remove the global @angular/cli from my system, but even after doing so, the 'ng -v' command still gives me a warning message: "Your global Angular CLI version (1.7.0) is greater than your local." Here's wha ...

Positioning the box at the exact middle of the screen

I'm trying to center an item on the screen using material ui, but it's appearing at the top instead of the middle. How can I fix this? import * as React from 'react'; import Box, { BoxProps } from '@mui/material/Box'; functio ...

Anticipating the outcome of various observables within a loop

I'm facing a problem that I can't seem to solve because my knowledge of RxJs is limited. I've set up a file input for users to select an XLSX file (a spreadsheet) in order to import data into the database. Once the user confirms the file, v ...

What is the best approach for defining variables in typescript?

Let's talk about creating a variable for a car: export class ICar { wheels: number; color: string; type: string; } So, which way is better to create the variable? Option one: const car = { wheels: 4, color: 'red', type: &apos ...

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 ...

Encountering an issue: JwPagination in angular 9 throws an error of "Cannot read property 'currentValue' of undefined"

Currently using Jw pagination with a page size that changes on 5, 10, or 15 using a dropdown. The Angular version being used is angular 9. The HTML code snippet for this functionality looks like: <div class="col-md-6"> <div ...