How can I add elements to a reactive array in Angular 2?

I have a system in place that retrieves documents and displays their metadata on a web page without any issues. However, I am looking to incorporate an "infinite scrolling" feature. After some research, I came across npm i angular2-infinite-scroll

Currently, I am using an observable for the documents and leveraging the async pipe within an *ngFor loop

document-list.ts

export class DocumentList implements OnInit {
    documents: Observable<Array<Document>>;
    chunck: number = 100;
    from: number = 0;
    keyword: string = "";

    constructor(private _documentService: DocumentService) {}

    ngOnInit() {
    this.documents = this._documentService.getDocuments(this.chunck, this.from, this.keyword);
    }
}

Using angular2-infinite-scroll, I have implemented a function that triggers when I reach the bottom of the page. My goal is to load more documents and display their metadata alongside the existing ones

onScroll() {
this.from = documents.length ... ?
//this.documents = this._documentService.getDocuments(this.chunck, this.from, this.keyword);
}

I'm uncertain if this approach is feasible with an observable. If I switch to using a simple array for documents like documents: Document[], I could potentially do something similar to

onScroll() {
this._documentService.getDocuments(this.chunck, this.from, this.keyword)
    .subscribe(documents => this.documents.push(documents));
}

Open to other suggestions or ideas?

Answer №1

If you want to experiment with using a Subject instead of an Observable, one approach could be...

Here is an example for your DocumentsService:

import { Subject } from 'rxjs/Rx';

export class DocumentService {
  _documentSubject = Subject.create();

  getNextTen() {
    // ... retrieve the document meta data here ... 
    this._documentSubject.next(documentMetaData);
  }

  get documentSubject() {
    return this._documentSubject;
  }

  //...
}

Then, in your documents component, you would implement it as follows:

 // ...
documents: Array = [];
documentRetriever: Subject<any>;

constructor(ds: DocumentService) {
  //Ideally, avoid doing this within the constructor, but the key point is
  //to subscribe to the Subject only once.
  this.documentRetriver = ds.documentSubject;
  this.documentRetriever.subscribe(newDocuments => {
    this.documents.push(newDocuments);
  })
}
onScroll() {
  this.ds.getNextTen();
}

Due to how RxJS Subjects function (serving as both Observables and Observers), you can pass data via .next() even after the Observable has been created.

You may still need to consider using the async pipe when binding to the documents array.

For further information on Subjects:

ReactiveX Docs

Getting started with RxJS: Subjects

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

Troubleshooting issues with exporting Excel in Angular 2

Having trouble exporting data in excel format using JExcelApi lib with an Angular 2 frontend and spring mvc backend? When deploying the backend to Tomcat and making a request via browser, the excel file exports correctly. However, when making the same http ...

Steps to fix the issue of 'Property 'foo' lacks an initializer and is not definitely assigned in the constructor' while utilizing the @Input decorator

What is the proper way to initialize a property with an @Input decorator without compromising strict typing? The code snippet below is triggering a warning: @Input() bar: FormGroup = new FormGroup(); ...

What is the best way to extract value from an `observable<void>`?

Recently, I have been exploring Angular and encountered a situation where I need to retrieve a value from a method using subscription. The method in question is designed to return an object with properties {ClientId, ClientSecret}, but I must admit that I ...

How can I ensure that PrimeNG is functioning properly?

I'm encountering some difficulties setting up PrimeNG correctly to utilize its rich text editor. Despite installing all the necessary components, it's still not functioning as expected. https://i.stack.imgur.com/4kdGf.png This is my package.jso ...

Guide on creating a TypeScript function that extracts specific properties from an object using a filter criteria

Look at the code snippet provided below. interface IEmployee { ID: string Employee: string Phone: number Town: string Email: string Name: string } // Retrieve all properties of type IEmployee let allProps = findSpecificItem<IEm ...

Transfer the value of a form field within the current object

I'm facing an issue when trying to pass a value to a personalized form validator: this.myForm = this.fb.group({ Id: [null], Password: ['', [Validators.required]], PasswordConfirm: ['', Validator ...

Step-by-step guide to designing a basic pagination/carousel using div elements in HTML and Angular 2

Hey there! I'm currently working on a project with an *ngFor in my template that generates multiple divs. <div *ngFor="let item of widgets" class="page-content widget-item"> <div>{{content}} </div> </div> I'd like to i ...

Is there a way to modify the format received from the backend Angular REST API?

Below is the code I am currently using: this.elService.getOne(id) .subscribe((result: ModelName) => { let test = this.datePipe.transform(result['birthDate'], 'mm/dd/yyyy') result['birthDate']= test console.log(result ...

What is the best way to show TypeScript code using "<code>" tags within an Angular application?

I am looking to showcase some TypeScript (angular code) as plain text on my website using prismjs. However, the Angular framework is executing the code instead. How can I prevent it from running? I have attempted enclosing it within pre and code tags wit ...

Error in ReactJS VSCode while integrating Cypress testing: The name 'cy' cannot be found

Currently working on a ReactJS Typescript project using NPM and VSCode. Despite all my Cypress tests running smoothly, I am encountering a syntax error in VSCode: Error: Cannot find name 'cy' Any ideas on how to resolve this issue? https://i.ss ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Adjusting linear gradient when the color picker is modified

My website has a default linear gradient over an image, which is controlled by the following HTML and TypeScript code: <header [style.background-image]="cv2HeaderStyle('0, 0, 0, 0.1', '0, 0, 0, 0.8')"></header> cv ...

Having trouble injecting HttpClient in a hybrid AngularJS/Angular app that has been upgraded with ngUpgrade? You may come across the error message "NullInjectorError: No provider for http_HttpClient!"

My AngularJS/Angular hybrid app, upgraded with ngUpgrade, has been functioning well. The new Angular components (downgraded) work seamlessly in the AngularJS app. However, I'm encountering an issue where the HttpClient module fails to instantiate. I ...

Ways to trigger an Angular function once and persist it even after the component is reloaded

Currently, I am learning Angular and have come across a particular issue. As far as I understand, everything placed within the `ngOnInit` method gets executed every time the component reloads. I have a timer function that needs to continue running even aft ...

Having trouble with installing the angular-4-data-table-bootstrap-4 package in NG 4.4.6 environment

I am currently working on an NG 4 project and my package.json indicates that I am using angular 4.4.6. I am attempting to include the angular-4-data-table-bootstrap-4 package as outlined below, but I keep encountering the error mentioned here that I can&ap ...

What are some effective ways to exclude multiple spec files in playwright?

Within my configuration, I have three distinct projects. One project is responsible for running tests for a specific account type using one login, while another project runs tests for a different login. Recently, I added a third project that needs to run t ...

Edge fails to access Webservice from file:/// host

When attempting to access a webservice that I've created in C# using Typescript and the fetch-api, everything works smoothly in Chrome and Firefox. However, in Edge, the access fails. I've tried both POST and GET methods in Edge, but neither are ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Include a log out option in the side menu of the ionic2 application

I am working with the sidemenu template to kick off my application. I aim to incorporate a button within the sidemenu that enables users to trigger a modal alert for confirming logout. Below is the code snippet: app.component.ts: import { Component, View ...

Accessing Properties or Methods in Angular2 Components

My application consists of 3 main components: PageMenu, LoginSession, and LoginForm. The purpose is to establish a connection between the variables in LoginSession and PageMenu, allowing for the proper functionality of the LoginForm component. PageMenu: ...