Generate a fresh Array by evaluating the properties provided by an Observable

I am working with an observable called myObservable$ that provides a specific array of objects:

[
 { "firstProp": "A", "secondProp": "NA", "available": false },
 { "firstProp": "B", "secondProp": "NA", "available": true },
 { "firstProp": "C", "secondProp": "Old", "available": false },
 { "firstProp": "C", "secondProp": "New", "available": false }
]

My objective is to create a new array by filtering based on 'firstProp' and 'available', and then pushing into a new structure:

[
 { imgSrc: 'pathTo/myImages/file1.svg', badgeStyle: val?.available ? 'fas fa-exclamation-circle fa-lg' : 'fas fa-check-circle fa-lg', cardLabel: 'First Label'},
 { imgSrc: 'pathTo/myImages/file2.svg', badgeStyle: val?.available ? 'fas fa-exclamation-circle fa-lg' : 'fas fa-check-circle fa-lg', cardLabel: 'Second Label'},
 { imgSrc: 'pathTo/myImages/file3.svg', badgeStyle: val?.available ? 'fas fa-exclamation-circle fa-lg' : 'fas fa-check-circle fa-lg', cardLabel: 'Third Label'},
]
The current solution works, but I believe there may be room for improvement:
const OBJ1 = { imgSrc: 'pathTo/myImages/file1.svg', badgeStyle: val?.available ? 'fas fa-exclamation-circle fa-lg' : 'fas fa-check-circle fa-lg', cardLabel: 'First Label'};

const OBJ2 = { imgSrc: 'pathTo/myImages/file2.svg', badgeStyle: val?.available ? 'fas fa-exclamation-circle fa-lg' : 'fas fa-check-circle fa-lg', cardLabel: 'Second Label'};

const OBJ3 = { imgSrc: 'pathTo/myImages/file3.svg', badgeStyle: val?.available ? 'fas fa-exclamation-circle fa-lg' : 'fas fa-check-circle fa-lg', cardLabel: 'Third Label'};



myObservable$.subscribe((value) => {
      value?.forEach((val) => {
        if (val?.firstProp === 'A') {
          this.myNewArray.push(OBJ1);
        } else if (val?.firstProp === 'B') {
          this.myNewArray.push(OBJ2);
        } else if (val?.firstProp === 'C' && val?.secondProp === 'New') {
          this.myNewArray.push(OBJ3);
        }
      });
    });
I am facing difficulties in handling the scenario where:

as I encounter two instances of 'firstProp' being 'C' with different types of 'secondProp' (Old and New). The challenge is to display 'exclamation' in badgeStyle when either one or both 'C' have "available": true, and to show a 'green-tick' for badgeStyle when both 'C' have "available": false.

Answer №1

If you decide to redefine the myNewArray property as an Observable, it offers advantages over your current solution. One key benefit is that you won't have to worry about manually unsubscribing from the Observable, as Angular handles this automatically for you. Let's illustrate this below...

//...

// Let's redefine myNewArray as an Observable
myNewArray$: Observable<Array<{ imgSrc: string; badgeStyle: string; cardLabel: string }>>;

// Initialization of the above code is necessary, which we will do in the
// component constructor
constructor() {
  //... Initialize myObservable property here
  // Assign myNewArray here
  this.myNewArray$ = this.myObservable$.pipe(
    map((value) => {
      if (val?.firstProp === 'A') {
        return OBJ1;
      } else if (val?.firstProp === 'B') {
        return OBJ2;
      } else if (val?.firstProp === 'C' && val?.secondProp === 'New') {
        return OBJ3;
      }
      // Make sure to handle the else statement to avoid a ts error
    })
  );
}

//...

To utilize this, you would use the async pipe in the html section of your component's code.

<ng-container *ngIf="(myNewArray$ | async) as newdata">
  <!-- Insert content here -->
</ng-container>

By implementing this approach, you can reduce memory leaks since Angular manages the unsubscription process when the component is destroyed.

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 utilize an npm package in TypeScript without a d.ts definition file?

Is it possible to use an npm package in TypeScript and Node.js without a .d.ts definition file? If so, how can I make it work? Currently, my code looks like this and I'm getting an error that says "cannot find module 'node-rest-client'" bec ...

The incorrect sequence of Angular/Protractor functions is causing issues within the tests

Trying to extract the values from a column in a grid and compare them before and after sorting can be tricky. I have two functions set up for this task - one to retrieve the initial column values, and another to check the order post-sorting. However, there ...

What is the correct way to specify Tesseract options for page segmentation?

I've been trying to understand how to configure tesseract options for page segmentation. I attempted to use tessedit_pageseg_mode: '1', but encountered a halt in the text recognition process. If I input it as number 1, the process completes, ...

Manage input from either mouse or touch events based on the event type

I've encountered a challenge with my general handler function that processes both mouse and touch events. Despite my efforts, Typescript keeps issuing errors due to the distinction between mouseEvent and touchEvent. function handleStopDrag(e: MouseEv ...

Mapping the changes in the checkbox of a material tree node

Check out this demo on StackBlitz: Tree View I'm having issues with the tree not displaying as desired. I would like it to look like this: Manager Sublist Manager 1 Manager 2 Manager 3 Could you please review and provide some advic ...

What is the best way to represent a directory structure in JSON using a C# data type?

My directory structure is as follows: v1 file1.txt file2.txt common common.txt I need to create a C# function that can traverse this directory structure and generate JSON output. The expected JSON format is like this: { "v1&qu ...

Filling in placeholder information for HTTP posting during development

I found a way to retrieve data from an endpoint fetchManufacturersData(): Observable<Manufacturers> { const requestBody = { 'num': 12 }; return this.http.post<Manufacturers>(manufacturersUrl, requestBody).pipe( catch ...

Create an HTML button on the homepage that directs users to the "about" page

I've been struggling to make a button in my Ionic app navigate to a different page upon clicking. Despite being new to Ionic, I've spent hours trying to solve this issue. Below is the HTML code in home.page.html: <ion-header> &l ...

What is the method in XState to trigger an event with the parameters send('EVENT_NAME', {to: 'a value from the context'})?

I want to send an event to a different spawned state machine using its ID, which I have stored as a string in a variable within the context. This state machine is neither the parent nor child. For example: context.sendTo = 'B_id' How can I use ...

What is the process for enabling Namespaces in CRA?

When creating a TypeScript React app, I used the following command: yarn create react-app my-app --template typescript This setup compiles my project using Babel and bundles it with webpack. Now, I want to utilize TypeScript namespaces, which are not nat ...

Is there a way to display the data from a URL as selectable options in a dropdown menu?

I have a URL containing an arrayList of data. My task is to fetch the data from this URL and display it as options in a dropdown menu, allowing users to select the desired option. I am aware that this can be achieved using the Get method, but I am facing d ...

Creating a TypeScript type or interface that represents an object with one of many keys or simply a string

I am tasked with creating an interface that can either be a string or an object with one of three specific keys. The function I have takes care of different errors and returns the appropriate message: export const determineError = (error: ServerAlerts): ...

Utilizing the patchValue function in Angular 2 Reactive forms to update elements within an FormControl Array

I am currently working with a reactive form in my project: myForm = this.fb.group({ ... } and I have been updating fields using buttons and functions like the following: (click)="update('someKey', someValue)" The update function is struct ...

TypeScript: By providing a variable CLASS as an argument to a function, automatically determine the return type to be an object of the specified class without any additional information

I am looking to create a function that accepts actual class objects themselves as arguments (within an object containing multiple arguments), with the return type of the function being inferred to be an instance of the class provided as the argument. In t ...

What could be the reason for the authentication issues in ionic/angular?

An authentication application has been created to receive user information and tokens (jwt) from the server. The data is stored locally and used for further computations within the app. For route guarding, if the token is available, it should proceed to th ...

How to make a unique array of arrays in Javascript without any repeated elements

Hello fellow programmers! I'm diving into Javascript and facing a little challenge that I need help with. Let me share some data that I'm dealing with: <pre> [ [ { "id": 2759178563, "title": "Ergonomic Paper Computer", ...

Tips for testing an Angular Service that utilizes AngularFireDatabase by utilizing Jasmine Spy/Mock

I am currently testing my data service, and while I can successfully test it using real services like AngularFireDatabase, I am facing issues with getting the mocked version to work for testing purposes. The DataStorage class in use is designed to combine ...

Using JSON objects as values in Angular2

When displaying a select option in my HTML, I am currently able to show a string as the value. However, I would like to have the entire JSON object as the value instead of just the string that is being displayed. Here is my code: <select *ngIf="car" c ...

Angular2 route-driven themes

Exploring Different Themes for Two Routes: /books and /paintings Seeking a Solution to Include Specific Stylesheet Links in index.html For the /books route, I wish to include: <link rel="stylesheet" href="/assets/css/reading-theme.css" /> And for ...

Exploring the detection of changes in variables using Aurelia

Is it possible to track changes to a variable using aurelia? While I know that I can detect changes in a variable's type using @observable, I am curious if it is possible to monitor changes in a variable's value, for example from a = 3 to a = 4, ...