How to link Array with Observable in Angular2 Typescript without using .interval()

Is it possible to achieve the same functionality without using the "interval()" method?

I would like to link an array to an observable, and update the array as well as have the observable monitor the changes.

If this approach is feasible, how can we incorporate the .distinctUntilChanged() function to ensure that new values are not emitted if they are the same, thereby preventing the "interval(10)" from becoming a bottleneck?

For reference, here is the Plunker: http://plnkr.co/edit/xlWSTz8gNfByTnT1REw5?p=preview

import {Component} from 'angular2/core';
import * as Rx from 'rxjs/Rx'

@Component({
    selector: 'a-webapp',
    template:`

    <div>
    <h2>{{name}}</h2>

    <button (click)="addToArray()">Add</button> <button (click)="resetArray()">Reset</button>
    <ul>
        <li *ngFor="let item of latest$ | async">{{ item | json  }}</li>
    </ul>

    {{ data | json }}

    </div>

    `
})
export class AppComponent {

    data = ["one", "two", "three"]
    data$: Rx.Observable<Array<string>>;
    latest$: Rx.Observable<Array<string>>;

    constructor() {}

    ngOnInit() {

        this.data$ = Rx.Observable.interval(10).concatMap(y => {
            return Rx.Observable.of(this.data)
        })

        this.latest$ = Rx.Observable.combineLatest(this.data$, (data) => {
            return data.map(d => {
                return d + " is a number"
            })
        })
    }

    addToArray() {
        this.data.push('more numbers')
    }

    resetArray() {
        this.data = ["one", "two", "three"]
    }

}

Answer №1

"... and observing the changes in the array to trigger reactions"

I believe it would be more advantageous for the observable to emit a new value each time the array undergoes a change

In this scenario:

export class AppComponent {
  data = ["one", "two", "three"];
  data$: Rx.BehaviorSubject<Array<string>>; // or data$: Rx.Subject<Array<string>>
  latest$: Rx.Observable<Array<string>>;

  constructor() {}

  ngOnInit() {
    this.data$ = new Rx.BehaviorSubject<Array<string>>(this.data);

    this.latest$ = this.data$.map(data => data.map(
      d => "" + d + " is a number"
    ));
  }

  addToArray() {
    this.data.push('more numbers');
    this.data$.next(this.data);
  }

  resetArray() {
    this.data = ["one", "two", "three"];
    this.data$.next(this.data);
  }
}

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 absence of jQuery is causing an issue in the webpack +Angular 4+ Asp Core template

I am currently working on a project that was created using the VS 2017 Angular 4 + Asp Core template. I have decided to incorporate a jQuery plugin into my project, which requires me to import jQuery. In my .ts file, I have included the following line of c ...

Error: The function User.findOne is not recognized

Currently, I am in the process of developing a Node.js API and aiming to implement JWT for login functionality. I have successfully set up the model and route, and while testing with Postman using the POST method, an error occurs upon sending the request. ...

Troubleshooting a cross-component property problem involving a fetch request within a subscription

My current objective is to utilize ActivatedRoute parameters to make a fetch request and update a class property with the fetched data. Progress has been made on making the request, but I am facing difficulties in getting the fetched data to the specific c ...

Obtaining context from a higher order component in the constructor of a child component: tips and tricks

In order to gain access to context throughout the application, I've implemented the following context provider: import React, { Component, useContext } from 'react'; import { appInitialization, Context } from "@microsoft/teams-js"; ...

Troubleshooting ng module not found error when deploying Typescript + Angular app on Azure App Service using Azure DevOps pipeline

My Typescript and Angular application runs perfectly when tested locally. Now, I'm in the process of setting up a deployment pipeline using Azure DevOps to build and release it to an App Service running on Linux (Node.js web app). Although the pipel ...

Ways to verify the functionality of a function utilizing a Subscription that yields no return value

I'm working with a TypeScript ModelService that has an edit function: edit(model: Model): Observable<Model> { const body = JSON.stringify(model); return this.http.put(`/models/edit/${model.id}`, body)); } Additionally, there is a TypeScrip ...

Using Angular: Binding Angular variables to HTML for display

I have a component with a ts file that contains HTML content as a variable. Let's say para1= <a href="www.google.com">sitename</a> more content I want to bind this paragraph in HTML as if it were actual HTML tags. sitename What is the ...

The function is attempting to access the 'lockDatabase' property of an undefined object, resulting in an error

I'm encountering an error due to the scope issue with 'this', and I'm struggling to find a solution. I attempted using the fat arrow, which solved the scope problem but created another issue where I lack a callback value that needs to b ...

Updating FontAwesome icon in Angular 10

I have successfully configured and implemented FontAwasome Pro in my Angular 10 project. <div class="update-split" [class]="testClass"><fa-icon [icon]="['fad', 'sync-alt']"></fa-icon></ ...

NestJS Exporting: Establishing a connection for PostgreSQL multi tenancy

I have been working on implementing a multi tenancy architecture using postgres. The functionality is all in place within the tenant service, but now I need to import this connection into a different module called shops. Can anyone provide guidance on how ...

Angular 2 Error: Unable to access the `subscribe` property of an undefined value

In my Angular 2 project, I have a single form that serves the purpose of adding a new event or editing an existing one. The logic checks the URL parameter to determine whether an ID is present. If an ID is found, it subscribes to the editEvent method from ...

Maximizing Jest's potential with multiple presets in a single configuration file/setup

Currently, the project I am working on has Jest configured and testing is functioning correctly. Here is a glimpse of the existing jest.config.js file; const ignores = [...]; const coverageIgnores = [...]; module.exports = { roots: ['<rootDir&g ...

What could be causing ESLint to run on its own configuration file while working with Typescript?

I have files named .eslintignore and eslintrc.js in close proximity. The contents of my ignore file are as follows: .eslintrc.js dist/* node_modules/* out-tsc/* However, when I access the eslintrc.js file, an error is triggered: Parsing error: ESLint was ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

What is the significance of the error message "Surprisingly in Angular Zone despite expectations"?

Ever since upgrading from Angular 2 RC4 to RC5, I've been encountering this error. Although it doesn't seem to impact the application's functionality, it keeps appearing in the console and may draw attention away from other errors. Does any ...

Definition of Typescript:Named Function Expression (NFE)

In my current project, I am examining the JS code snippet below as part of creating a .d.ts file: BatchBuffer.js var Buffer = function(size) { this.vertices = new ArrayBuffer(size); /** * View on the vertices as a Float32Array for posi ...

Unable to automatically redirect to portal upon submission of form

After successfully logging the user into my app, I want to redirect them imperatively to the portal page. However, when I use the router.navigate() function, a few things happen that are causing issues. First, the app redirects to /portal. Then, it immedia ...

How to send an ngFor element to a pipe in Angular 2 as an argument?

When attempting to pass an ngFor item into a pipe as a parameter, I encountered an error: Error: Call to Node module failed with error: Error: Template parse errors: TypeError: Cannot read property 'toUpperCase' of undefined ("{{name}} ng-cont ...

Globalizing Your Angular 4 Application

Looking for a way to enable Internationalization (i18n) on button click in Angular 4 with support for at least four languages? I attempted to use the Plunker example provided here, but it seems to be encountering issues: ...

Unable to activate the AWS IoT security audit using CDK

I'm trying to activate the AWS IoT security audit using a CDK stack, but I'm encountering some issues. Initially, I referred to this documentation for the interfaceAuditCheckConfigurationProperty and implemented the following CDK code to enable ...