Retrieve a particular item using the NGXS selector and incorporate it into the template

I am retrieving stored configuration settings from an API. Each setting includes an 'ID' and several properties like 'numberOfUsers', etc. I am utilizing NGXS for managing the state.
My goal is to specifically fetch the 'numberOfUsers' property and use it in my template. However, I am facing an issue where initially the subscription returns 'undefined' for a brief moment before providing the actual data (refer to image). I have attempted using mapping as well, but I am uncertain about the best approach and how to effectively display the data in my template.

Below is my current code:

@Select(SettingsState.getSettings)
settings$!: Observable<Settings[]>;

settingsChanged!: Settings[];

ngOnInit(): void {
  this.store.dispatch(new GetSettings(this.settingsId));

  this.settings$.subscribe((data: Settings[]) => {
        console.log('data', data);
        return this.settingsChanged = data;
      }
  );
}

console.log('settingsChanged', this.settingsChanged);

https://i.stack.imgur.com/qfZ9O.png

Answer №1

Give this a try, it could be useful!

Filter: Helps to eliminate null responses.

Map: Selects only the desired properties.

import { filter, map } from 'rxjs/operators';

this.settings$.pipe(
  map((data) => {
    if(data) {
      return {
        id: data.ID,
        attempts: data.numberOfUsers,
        key: data.others,
      };
    }
  }),
  filter(res => res && res != undefined)
).subscribe((data: any) => {
  console.log('data', data);
  alert(data.id);
  return this.settingsChanged = data;
});

See a working example here: link

Best of luck!

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

Structure of document

Could anyone clarify for me the meaning of (callback[, thisObject]); that is mentioned in the TypeScript documentation here? I am particularly curious about the brackets themselves [, ]. ...

What is the best way to create a routerlink that is both single-clickable and double-clickable within an

There have been numerous instances where a similar question has been raised, but I am unable to make this work. Despite looking at various answers such as this one on Stack Overflow that don't seem to work for most users. While this may not be specifi ...

Develop a component library for Angular 2 without incorporating inline styles

I recently came across an interesting article about developing an Angular 2 component library that utilizes inline styles. Is there a method to create a library in Angular 2 without relying on inline styles? I also stumbled upon another resource, but it d ...

Overriding a generic property in Typescript allows for a more

I'm troubleshooting an issue with my code: class Base<T> {} class Test { prop: Base<any>; createProp<T>() { this.prop = new Base<T>(); } } const test = new Test(); test.createProp<{ a: number }>(); test.pr ...

Tips on transferring a child Interface to a parent class

Here is my code snippet: LocationController.ts import {GenericController} from './_genericController'; interface Response { id : number, code: string, name: string, type: string, long: number, lat: number } const fields ...

Loop proceeding without waiting for promise resolution containing nested Firebase call

I am currently facing an issue with making Firebase database calls within a loop and an outer Firebase call. The inner database call utilizes data returned from the outer call and the loop, hence it is nested inside the outer one. The goal is to set the re ...

ng2 - Comparing DevExtreme and Telerik Kendo UI

Our team is embarking on a new software project utilizing Angular2, typescript, and HTML5. We are considering two options for UI components: - DevExtreme - Telerik Kendo UI Which of these would be the best choice in your opinion? Thank you! ...

"Exploring the world of npm packages alongside the powerful angular-cli tool

Is it better to package angular2 components in an npm module with the source files (*.ts, *.css, *.html) or the webpack compiled version for use in applications compiled with angular-cli@webpack? What should actually be published in the npm package? The r ...

Transferring information between Material-UI Stepper components with the help of React Hooks

I am working on a complex multi-step form that needs to be built in React using Formik, Material-UI, functional components, and the getState hook. import React, { useState, Fragment } from 'react'; import { Button, Stepper, Step, StepLabel } fro ...

What steps should I follow to set JSONP as the dataType for a request in an Angular $http service?

I have a good understanding of how to use jQuery's $.ajax: $.ajax({ url: //twitter endpoint, method:"GET", dataType:"jsonp", success:function() { //stuff } }); Is there a way to set the JSONP datatype for an angular $http service reque ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Error: Failed to execute close function in inappbrowser for Ionic application

Working on integrating the "in-app-browser" plugin with my Ionic project. Check out the code snippet below: const browser = this.iab.create(mylink, '_blank'); browser.on('loadstop').subscribe( data => { if ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

A step-by-step guide on retrieving the present date and time using TypeScript

Details This is my first time creating a VSCode extension using TypeScript, and I am having trouble displaying the current date/time in an information message. My Attempts I have searched through VSCode key bindings for any references to date/time, as w ...

How come the splice method is changing the value of the original object?

There's something strange happening with this code I'm trying out. Code: const x = [{ a: 'alpha', b: 'beta' }, { a: 'gamma' }]; const y = x[0]; y.a = 'delta'; x.splice(1, 0, y) console.log(x) Output: [ ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...

Incorporate Select2 functionality within the Angular2 application

I'm currently working on incorporating the Select2 plugin into my Angular2 application. Successfully, I have managed to set up select2 and transform my multiple select fields as expected. However, I am now facing a challenge in retrieving the selected ...

Create a randomized item for experimentation in NodeJs using an interface

Looking for a NodeJs package that can generate fake data in all required fields of a complex object described by a set of typescript interfaces, including arrays and sub-interfaces. Any recommendations? ...

Angular Service worker mishandles http redirects (302)

In my current project, I am implementing Angular and Spring Boot technologies. When I build the project, Angular generates the service worker for me. The issue arises when I use an external service (auth2) and my backend redirects to the login page after ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...