Using TypeScript, add an observable to an array of observables using RxJS

Can someone explain how to include Observable<News> in an array of observables?

newsArray: Observable<Array<any>>;

addNews(newsId: number) {
   let news = this.newsService.getNewNews(newsId); // this results in an Observable<News>.

  //How can I add `news` to `newsArray` so it can be shown in the UI?
}

HTML:

<li *ngFor="let item of (newsArray | async)">
  <div>{{item.Id}}: {{item.DataValue}}</div>
</li>

Are there any other operators that would help in this situation?

I attempted to use BehaviourSubject but it only displays one value at a time. I want to showcase all items being added to the array.

Answer №1

If you want to stay updated with the latest news, you can utilize a scan function

news$:Observable<any>
loadMore$=new Subject<number>()

ngOnInit(){
 this.news$=this.loadMore$
 .switchMap((newsId)=>this.newsService.getNewNews(newsId))
 .scan((acc,curr)=>{
    acc.push(curr)
    return acc
 },[]).startWith(null)
}

addNews(newsId: number) {
  this.loadMore$.next(newsId);
}

HTML

<li *ngFor="let item of (news$ | async)">
  <div>{{item.Id}}: {{item.DataValue}}</div>
</li>

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

Having trouble integrating SVG icons into my Angular project

I'm encountering an issue with adding icons that I've designed in Figma to my web application. Some of the icons are displaying correctly while others are not. Here is the code snippet I am using to add the icons: .dx-icon-info { mask-image: ...

Decipher the enigmatic bytea encoding of a Java int[][] array and restore it to its original form using

Simply put, I have a task to transform a bytea from PostgreSQL to an int[][] either using Java 6 or SQL. If you need some background information, you can read further below, but that's the gist of it. Background A former team member created a bean ...

What could be causing the "Permission Denied" error to occur when attempting to post data to Firebase realtime database using Angular?

I've been working on a bookshop application using Angular 9.0 and Firebase Realtime Database. So far, I've been able to handle writing and reading data with the default rules. { "rules":{ ".read": true, ".write": true } } No ...

Find the total of values in an array that may be null or undefined

In this scenario, I have an array that looks like this: myData = [[2, null, null, 12, 2], [0, 0, 10, 1, null], undefined]; The goal is to calculate the sum of each sub-array, resulting in an array like this: result = [16, 11, 0]. The ...

The icon for caret down in FontAwesome is not displaying when using ngClass

I am experiencing an issue where only the fontawesome caret up is displayed when sorting a field, but the fontawesome caret down is not showing. I have provided the code snippet below. HTML <th (click)="sort('ref')">Ref {{reverse}} & ...

Angular's ng serve is experiencing issues with mark-compacts near the heap limit, leading to an unsuccessful allocation

Encountering an issue while running ng serve in my Angular project. However, ng build --prod seems to be working fine. <--- Last few GCs ---> [4916:00000276B1C57010] 588109 ms: Scavenge (reduce) 8180.7 (8204.3) -> 8180.6 (8205.1) MB, 3 ...

Incorporate a CSS framework into the Angular vendor bundle

My current situation : The website is built with Angular 4 Started using Angular Starter Kit Utilizing Semantic UI as the CSS framework The challenge I'm facing : Integration of Semantic UI into webpack is not having any impact. Steps I've ...

The Effect feature in Angular NgRx can sometimes lead to a never-ending loop

One thing I want to clarify is that I am still struggling to fully grasp the functionality of rxjs's operators. Despite studying them, when I use switchMap, mergeMap, or map in practice, the outcome appears to be the same. The code snippet below resu ...

Generating JSON data with Ruby for a collection of items

I'm a beginner with Ruby. My goal is to generate a JSON file for a set of elements. To achieve this, I am utilizing the each function to fetch the data. The desired structure of the JSON file for a 4 element array is as follows: '{ "desc" ...

Is it possible to deactivate the click event on an Angular mat table row?

Within my Angular mat table, I have implemented code that expands a table row when clicked. However, I now need to prevent certain rows from being clickable based on the "element.disable" property. <ng-container matColumnDef="id"> <th mat-hea ...

Using JavaScript's indexOf method with multiple search values

I have a data set that includes various duplicate values ["test234", "test9495", "test234", "test93992", "test234"] I am looking to find the positions of every instance of test234 in the dataset Although ...

Guide on assigning JSON response values to TypeScript variables in Angular 4

I'm just starting with Angular 4 and I'm attempting to retrieve a JSON value using http.post. The response I'm receiving is: {"status":"SUCCESS"} component onSubmit(value: any) { console.log("POST"); let url = `${this.posts_Url}`; t ...

Issue with launching Angular 6 project

I attempted the solution from this link, but unfortunately, it did not work for me. I have cloned a project from GitLab and am attempting to run it. First, take a look at the output of my ng version command: https://i.sstatic.net/qxRzk.png. The project i ...

Creating an index for a JSONB column in Postgres that contains an array of JSON values

In my postgres database, I have a table named "employee" with a JSON column called "mobile". This column stores an array of JSON values representing employee mobile numbers. e_id(integer) name(char) mobile(jsonb) 1 John [{\"mo ...

What steps can be taken to further personalize this pre-existing jQuery sorting solution?

After coming across a solution for adding sorting capabilities to jQuery (source: jQuery sort()), I decided to tweak it to handle strings of variable lengths. Although the modified function sorts in ascending order, I found it quite effective. jQuery.fn.s ...

What is the best way to utilize a variable from a function when using ngClass in Angular?

Currently, using Angular 4, I'm attempting to utilize ngClass by comparing a variable called sender which is created within a function with an object from an array known as item.sender. Below is the snippet of HTML code: <ion-card *ngFor="let ite ...

Exploring Angular observables: Tips for gathering specific fields from a nested array within an object into a new array

I am working on parsing a JSON object and extracting specific fields to create their own array. My goal is to loop through the provided object and gather the 'appSupportedId' values into a separate array. An issue has arisen, leading to an ERRO ...

Issue: Execution terminated with error code 1: ts-node --compiler-params {"module":"CommonJS"} prisma/seed.ts

Whenever I run npx prisma db seed, I encounter the following error: Error message: 'MODULE_NOT_FOUND', requireStack: [ '/run/media/.../myapp/prisma/imaginaryUncacheableRequireResolveScript' ] } An error occurred during the execution ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...