Utilize information gathered through subscription to populate the List

Objective:
Achieve the retrieval of output data

 { age: 4, name: 'Foo' }
 { age: 7, name: 'Bar' }

and subsequently utilize this output data in the variable list labeled as "PersonList: Person[] = [];"

Challenge:
I have attempted various solutions to implement the output data into the variable PersonList but have been unsuccessful.

Currently, I am unsure how to proceed with this task.

Stackblitz Link:
https://stackblitz.com/edit/ztwnpx?file=index.ts

Thank you!

import { of } from 'rxjs';
import { distinct } from 'rxjs/operators';

interface Person {
   age: number,
   name: string
}

of<Person>(
    { age: 4, name: 'Foo'},
    { age: 7, name: 'Bar'},
    { age: 5, name: 'Foo'},
  ).pipe(
    distinct((p: Person) => p.name),
  )
  .subscribe(x => console.log(x));

// displays:
// { age: 4, name: 'Foo' }
// { age: 7, name: 'Bar' }

Answer №1

If you want to make use of the toArray operator for your array:

import { distinct, toArray } from "rxjs/operators";

let people: Person[];

of<Person>(
  { age: 4, name: "Foo" },
  { age: 7, name: "Bar" },
  { age: 5, name: "Foo" }
)
  .pipe(
    distinct((p: Person) => p.name),
    toArray()
  )
  .subscribe(result => {
    people = result;
  });

console.log(people);

Check out the Forked Stackblitz example

Alternatively, you can utilize an Observable in a simpler way:

const people$: Observable<Person[]> = of<Person>(
  { age: 4, name: "Foo" },
  { age: 7, name: "Bar" },
  { age: 5, name: "Foo" }
)
  .pipe(
    distinct((p: Person) => p.name),
    toArray()
  );

Answer №2

It seems like there might be a missing piece here, but the solution involves placing the data into an array...

const peopleArray = []; // start with an empty array

from<Person>(
    { age: 10, name: 'Alice'},
    { age: 25, name: 'Bob'},
    { age: 15, name: 'Alice'}
  ).pipe(
    distinct((person: Person) => person.name),
  )
  .subscribe(item => peopleArray.push(item)); // add each item to the array

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

The Heart of the Publisher-Subscriber Design Paradigm

After reading various online articles on the Publisher-Subscriber pattern, I have found that many include unnecessary domain-specific components or unreliable information inconsistent with OOP standards. I am seeking the most basic and abstract explanatio ...

Disable automatic focus on first button in PrimeNG Dialog

I am looking for a way to stop the autofocus on the first input element when opening the PrimeNG dialog. <p-dialog header="User Details" [(visible)]="displayDialog" [responsive]="true" showEffect="fade" [modal]="true" (onAfterHide)="onDialogHide ...

Looking to substitute the <mark> element within a string with the text enclosed in the tag using JavaScript

In need of help with replacing tags inside a string using JavaScript. I want to remove the start and end tags, while keeping the content intact. For example, if my input string is: <div class="active"><mark class="active-search-position">The ...

Angular nested Tree is not appearing as anticipated

The tree structure I created using Angular Nested Tree component is not displaying the User Interface as expected. The words "fruit" and "vegetables" are overlapping with the text "expand more", making it difficult to read. Can someone help me fix this UI ...

Adding an additional element to an incoming array in Angular/Typescript/RxJS - a step-by-step guide

I recently encountered a challenge in my RxJS code involving the transformation of a list of JSON objects into items for a drop-down list. this.folders$ = this.folderStore.folders$.pipe( map((folders: GdFolder[]) => { const data = folders.map(fold ...

Angular: utilizing two instances of the <router-outlet> within a single component

Disclaimer: Despite finding a similar question on Stack Overflow with an accepted answer that did not solve my issue, I am still facing a problem. The challenge I am encountering is needing to use the same "router-outlet" twice in my main component. Howev ...

Angular users should be cautious of the 'grid zero width' warning that may arise when employing ag-Grid's sizeColumnsToFit() on multiple ag-Grids simultaneously

I'm encountering an issue with ag-grid where I see the following warning in the console. Despite conducting some research, none of the solutions I found have resolved my problem. It appears that there may be a memory leak within my application based o ...

Disregard the validator rule for the FormBuilder property if a different property is configured as false

Is it possible to bypass a validator rule in Angular 2-5's FormBuilder if another property within the FormBuilder group is set to a certain value? For example, consider the following code snippet: this._fb.group({ "stake": [data.stake, ...

I'm facing an issue in Angular 4 where the routing for a child component is

I'm currently working on implementing routing in my Angular app for movies. I've set up a movie component and an edit movie component. The edit movie component is nested within the movie component, as shown in the folder structure below: https: ...

simulate the behavior of a promise function within a class

I'm facing an issue with this class structure: @Injectable() class ServiceOne { method1(): Promise<any>{ return new Promise((resolve,reject)=>{ // performing some operations let value = 1; resolve({'value':1}); }); } ...

The mat-select value is experiencing issues when including spaces and is not functioning as

There seems to be a minor mistake that I can't seem to locate. Below is the form in question: <mat-card> <form #f="ngForm"> <mat-card-content> <mat-form-field> <mat-select [ngModel]="data.variab ...

Leverage functionalities from the rxjs npm package within an Angular application without the need for npm install

In the midst of updating my Angular 4 application to use rxjs version 6.3+, I discovered that many changes in rxjs are causing issues with my existing codebase. One of the new features we need to implement requires this update, but it's proving to be ...

Issues with JSONPATH in typescript failing to grab any values

Searching for a specific config item validity using JSON path can be achieved by specifying the key name condition. This process works seamlessly on platforms like , accurately extracting the desired value: https://i.sstatic.net/2ffAAnNM.png In Typescrip ...

Firebase Integrations: How to Handle Errors in External API Calls within Firebase Functions

My current challenge involves retrieving data from an external API using Firebase functions and displaying it in an Angular application hosted on Firebase. Billing is enabled for the project. The API call works fine on localhost, but fails to fetch data wh ...

Utilizing checkboxes for toggling the visibility of buttons in Angular

I want to dynamically show or hide buttons based on a checkbox. Here is the HTML code I am using: <input class="form-check-input" [(ngModel)]="switchCase" type="checkbox" id="flexSwitchCheckChecked" (change)=" ...

Saving large amounts of data in bulk to PostgreSQL using TypeORM

I am looking to perform a bulk insert/update using TypeORM The Test entity is defined below: export class Test { @PrimaryColumn('integer') id: number; @Column('varchar', { length: 255 }) testName: string; } I have the f ...

Achieving a successful Reset Password functionality with ASP.NET Core and Angular

I've been working on setting up password recovery for users who forget their passwords and need to reset them. One issue I'm facing is figuring out how to properly generate the recovery link that is sent to the user via email. Should the link le ...

Implementing Observable lambdas in Angular templates for easy function calling

Within a component, I have the following code snippet: public hasFoo$: Observable<(name: string) => boolean> = ... Now, I would like to use this multiple times in my template with a stepper: <mat-vertical-stepper> <mat-step *ngIf="ha ...

A guide on integrating a data deletion feature in Angular applications

On our website's edit page, there is a list of mat cards/workspaces with an edit icon in the top corner of each workspace. Clicking on the edit icon will take you to the edit page for that specific workspace. Within this edit page, there is a delete b ...

Exploring methods to successfully upload a blob to Firebase and modify it using cloud functions

For days now, I've been attempting to successfully upload a file to firestorage using firebase functions but haven't had any luck. This is the progress I've made so far: export const tester = functions.https.onRequest(async (request, respons ...