Blast information to Observable

To view the code sample, visit the following link: stackblitz

In my data service, data is fetched asynchronously from a global object (in the actual project, data is emitted via EventEmitter).

The structure of the service is as follows:

import { Injectable } from '@angular/core';

import { Observable, Observer } from 'rxjs';

class DataEmitter {
  public eventCallback: () => void;

  constructor() {
    setInterval(() => {
      if (this.eventCallback) this.eventCallback();
    }, 1000);
  }
}

let emitter = new DataEmitter();

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private counter = 1;

  public dataSource = new Observable<number>((observer: Observer<number>) => {
    emitter.eventCallback = () => {
      observer.next(this.counter++);
    };
  });

  constructor() {}
}

The respective Component subscribes to the observable for data display:

import { Component, VERSION, OnInit } from '@angular/core';

import { DataService } from './data.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;

  presentableData: number[] = [];

  trigger = 0;

  constructor(private dataService: DataService) {}

  ngOnInit(): void {
    this.dataService.dataSource.subscribe((num) => {
      console.log('presentableData.length: ' + this.presentableData.length);
      this.presentableData.push(num);
    });

    setInterval(() => this.trigger++, 10000);
  }
}

Currently, the view does not update every second as expected. The global data emitting object seems to be outside the scope of the Observable subscribe method, resulting in the Component not re-rendering on data arrival. However, triggering it with another bound variable displays all the data.

Is this behavior normal or expected, or is it a bug within Angular?

Answer №1

If you're dealing with data that originates from an event listener, you can use the following code snippet:

scroll$ = fromEvent(window, 'scroll')

This code snippet effectively converts an event listener into an observable.

Additionally, RxJS provides subjects to cover data emitting functionality:

obs$ = new BehaviorSubject<number>(0); // Retains and emits the last value upon subscription
obs$ = new Subject<number>(); // Does not retain a value and does not emit upon subscription

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

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

What steps should I take to successfully launch an ASP.NET Core Angular Template without encountering any errors?

While working on a new ASP.NET Core 3.1 Angular Project using Visual Studio for Mac (v8.4.8) and running it in debug mode, I encountered an issue resulting in the following exception: "An unhandled exception occurred while processing the request Aggregat ...

A guide on combining multiple arrays within the filter function of arrays in Typescript

Currently, I am incorporating Typescript into an Angular/Ionic project where I have a list of users with corresponding skill sets. My goal is to filter these users based on their online status and skill proficiency. [ { "id": 1, ...

Ending the Infinite Scroll in Ionic 3 When Data Runs Out

I am having an issue with my json data where I need to figure out how to stop the infinite scroll once there is no more data available. Can anyone help me implement this feature? Below is the code snippet for reference: handleDataLoad(currentCount) ...

Creating ngModel dynamically with *ngFor in Angular 2: A guide

I've been struggling with this for the past couple of days - how can I have a new ngModel for each iteration within an *ngFor loop? The idea is that I load a list of questions, and within each question there are 2 propositions. Here's the HTML: & ...

Issue with Angular Material date picker: Date Parsing UTC causing dates to display as one day earlier

After exploring numerous threads related to this issue and spending several days trying to find a solution, I may have stumbled upon a potential fix. However, the workaround feels too messy for my liking. Similar to other users, I am encountering an issue ...

Tips for ensuring the HTML checkbox element is fully loaded before programmatically selecting it

When a user accesses the page, I want certain checkboxes to be automatically checked. To achieve this, I am storing the IDs of the HTML checkbox elements in a service. Upon entering the page, the service is utilized to retrieve an array containing these ID ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Ways to exit a loop in TypeScript

I've encountered an issue with the following code where I am struggling to break the loop under certain conditions. Desired Outcome: An error message should display, allowing the user to close it and remove the escalation node correctly. Actual Outc ...

Checking to see if the prop 'isChecked' has been modified

I'm currently facing a challenge with testing whether a class's prop value changes after clicking the switcher. Below is the component class I am working with: import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core&a ...

`The flaw in filtering logic - an analysis`

Looking to find matching records within two Lists. We have a List called allAnimals with attributes like animalId, and another List named domesticAnimals also containing animalId. The goal is to compare the two lists and create a new list where the anima ...

Tips for simulating a "nested" angular service within a component using jest

I'm looking to create a unit test for an Angular Component using Jest. The component, which is built on Angular version 7.2.0, interacts with a nested service through this.api.manageUser.getUsersStats(). My goal is to verify if this method is being ca ...

Tips for monitoring/faking method invocations within an Angular 5 service's constructor

My service involves making 2 method calls in the constructor: constructor(private http: HttpClient) { this.apiURL = environment.apiURL; this.method(); this.method2().subscribe(); } I am facing difficulties testing this service in the Test ...

Typescript: Declaring object properties with interfaces

Looking for a solution to create the childTitle property in fooDetail interface by combining two properties from fooParent interface. export interface fooParent { appId: string, appName: string } export interface fooDetail { childTitle: fooParent. ...

Troubleshooting OAuth in Angular: Preventing Double Reloads and Redirects

My Angular app is utilizing OAuth2 Google authentication. I have set up an authGuard for specific endpoints, but I have noticed a flickering or double loading issue on the same page. Additionally, it appears that the console is being cleared. How can I tro ...

Are the polyfills.ts files absent from the Angular 2 ASP.NET Core project I built using the VS template?

Just starting out in Angular development, I decided to use the Visual Studio 2017 Professional template to kickstart an Angular 2 application with ASP.Net Core: https://i.sstatic.net/RA6xZ.png Encountering an issue with the app not running on Internet Exp ...

How to define an array of objects in data using Vue.js and TypeScript

Encountering errors when attempting to declare an array of objects in Vue.js 3 + TypeScript. The code snippet includes a template, script, and style sections. <template> <ul > <li v-if="!items.length">...loading</li> ...

Alter the data displayed by the Radio button using Angular when the Submit button is clicked

I've encountered an issue where I need to alter a div based on the selection of a radio button. Currently, it changes instantly upon button click, rather than waiting for submission. My desired outcome is for the value to be submitted when the button ...

"Enhance your user experience with dual notifications using the Angular2-to

Whenever I utilize the angular2-toaster packages, I find myself receiving duplicate notifications. Below is an example showcasing the usage of this package. I am unsure why this issue occurs, but I have noticed that simply reloading my angular2 applicatio ...

What is the best method to extract a query parameter from the ActivatedRoute snapshot within the Angular app component?

Is there a way to retrieve a query parameter in my app.component synchronously without using ActivatedRoute's queryParamMap observable? I tried using the route snapshot like this: const param = this.route.snapshot.queryParamMap.get('param') ...