Is it possible to continually produce sine wave information using an Angular service and then integrate it into a component?

I am working on a component that uses an injected service to fetch static mock data. I want to enhance this by adding the capability to generate new data at various intervals and send this time series data to the component as it is created.

However, I'm struggling to find a way to achieve this.

The only thing I am certain of is that the data object for the component must remain immutable.

If anyone could point me in the right direction, I would greatly appreciate it. At one point, I considered using a service worker, but that seemed excessive for a simple mock-up. In the future, this service will interact with data sources over the internet using streams. But for now, I just need to simulate a stream of data flowing from the service to the component for UI development and prototyping purposes.

plotter.component.ts:

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

import { MockDataService } from '../../services/mock-data/mock-data.service';

@Component({
  selector: 'app-plotter',
  templateUrl: './plotter.component.html',
  styleUrls: ['./plotter.component.css']
})
export class PlotterComponent implements OnInit {

  single: any[];
  multi: any[];

  // rt needs to be an immutable object array
  // rt needs to be updated with data from MockDataService
  rt: any[];

  view: any[] = [700, 400];

  // options
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'Country';
  showYAxisLabel = true;
  yAxisLabel = 'Population';

  colorScheme = {
    domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
  };

  autoScale = true;

  constructor(private mockDataService: MockDataService) {
    this.single = mockDataService.getSingle();
    this.multi = mockDataService.getMulti();
  }

  ngOnInit() {

  }

  onSelect(event) {
    console.log(event);
  }

}

mock-data.service.ts

import { Injectable } from '@angular/core';
import { single, multi } from '../../mock-data/plot-data';

@Injectable({
  providedIn: 'root'
})
export class MockDataService {

  constructor() { }

  getSingle() {
    return single;
  }

  getMulti() {
    return multi;
  }

  // Generate sine wave data here
  sineWave(pAmplitude, pFrequency) {

  }

}

Answer №1

To ensure seamless updates to your arrays, consider storing them in a Subject or BehaviorSubject. By returning this as an Observable and subscribing to it, any changes made using the setter in the service will automatically update the component's copy of the arrays.

plotter.component.ts:

import { Component, OnInit } from '@angular/core';
import { MockDataService } from '../../services/mock-data/mock-data.service';
import { timer, Subscription } from 'rxjs';

@Component({
  selector: 'app-plotter',
  templateUrl: './plotter.component.html',
  styleUrls: ['./plotter.component.css']
})
export class PlotterComponent implements OnInit {
  /*
   The timer function accepts a second argument to determine frequency of value emission.
   In this case, the method calls occur initially after 1 second and subsequent calls happen every 10 seconds.
  */
  const source = timer(1000, 10000);
  let subscription: Subscription;

  single: any[];
  multi: any[];

  pAmplitude: number = 0;
  pFrequency: number = 0;

  // rt should be an immutable object array
  // Update rt with data from MockDataService
  rt: any[];

  view: any[] = [700, 400];

  // options
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'Country';
  showYAxisLabel = true;
  yAxisLabel = 'Population';

  colorScheme = {
    domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
  };

  // line, area
  autoScale = true;

  constructor(private mockDataService: MockDataService) { }

  ngOnInit() {
      this.mockDataService.getSingle().subscribe( data => {
          this.single = data;
      });

      this.mockDataService.getMulti().subscribe( data => {
          this.multi = data;
      });

      this.startPolling();
  }

  ngOnDestroy(): {
      this.subscription.unsubscribe();
  }

  startPolling(): void {
      this.subscription = source.subscribe(
          () => {
                  // Increment values of both variables then
                  // Invoke the service method passing in the updated variables
                  this.pFrequency += 12;
                  this.pAmplitude += 24;
                  this.mockDataService.sineWave(this.pAmplitude, this.pFrequency); 
                }
      );
  }

  onSelect(event) {
    console.log(event);
  }

}

mock-data.service.ts

import { Injectable } from '@angular/core';
import { single, multi } from '../../mock-data/plot-data';
import { Observable, BehaviorSubject, } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MockDataService {

  private single: BehaviorSubject<any[]> = new BehaviorSubject([]);
  private multi: BehaviorSubject<any[]> = new BehaviorSubject([]);

  constructor() { 
  }

  getSingle(): Observable<any[]> {
    return single.asObservable();
  }

  setSingle(data: any[]): void {
      this.single.next(data);
  }

  getMulti(): Observable<any[]> {
    return multi.asObservable();
  }

  setMulti(data: any[]): void {
      this.multi.next(data);
  }

  // Generate sine wave data here
  sineWave(pAmplitude, pFrequency) {
      console.log('set new pAmplitude: ', pAmplitude);
      console.log('set new pFrequency: ', pFrequency);
  }

}

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

Retrieving array-like form data in a TypeScript file

I need assistance with passing form inputs into a typescript file as an array in an ionic application. The form is located in question.page.html <details *ngFor="let product of products;"> <ion-input type="text" [(ngModel ...

The import of my library using package.json exports is failing due to TypeScript compilation errors

I am currently developing a JavaScript library that I want to make importable via script tags, ES6 imports, and traditional Node requires, with or without TypeScript or any build systems. However, I am facing challenges in achieving this. Within my packag ...

Exploring the utilization of CSS host selectors with Angular4 to target direct child elements

Within my app.component.css file, I currently have the following code snippet: * ~ * { margin-top: 24px; } This rule actually adds some top margin to all elements that come after the first one. However, this is not exactly what I intend to achieve. My ...

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...

operating efficiently even when producing an incorrect output type

Exploring Typescript for the first time on Codepen.io has left me puzzled. I'm unsure why, despite defining the function signature and return type with an interface, I am able to return a different type without encountering any errors. Is there somet ...

Unable to set dimensions for an image within an input field using TypeScript

My goal is to retrieve and assign the height and width of an image to hidden text inputs in HTML, as shown below: The purpose is to obtain the height and width for validation. HTML: <input type="file" class="file" #introIcon id="uploadBtn" (change)=" ...

Navigating to a Nested Route in Angular 4

I am currently working on setting up a simple list with details using Angular 4. The routes I have set up are as follows: { path: 'list', component: ListComponent, children: [ { path: 'detail', compon ...

Having trouble adding @angular/fire to my Angular project

Having trouble adding Firebase authentication to my Angular project, specifically when running npm install @angular/fire. I keep encountering the following error: > npm ERR! code ERESOLVE > npm ERR! ERESOLVE unable to resolve dependency tree > ...

Exploring a collection of objects in your Angular 4 Firebase database via iteration

I've encountered some errors while attempting to iterate through my database. Despite trying various solutions, I have been unable to resolve the issue. Below you can find snippets from my code: order-details.component.html <header class="masth ...

Guide to creating a generic that captures the prop types of a given component

Is there a way to create a function that accepts a component and uses its prop type as the type of the second parameter? For example, if I provide a component with the type React.FunctionComponent<IMovieShowcase> How would I go about extracting the ...

What is the best way to create a props interface that includes state and setState values that are being

As I dive deeper into TypeScript, a hurdle has appeared in my app. Upon introducing React.FunctionComponent to my components, an issue arose with my Props interface. The error message reads: Type '({ value, setValue, }: Props) => JSX.Element' ...

Is it necessary to cancel the subscription of httpClient in the component?

Amidst the myriad of questions and comments surrounding this topic, I find myself with a more particular inquiry, although it may come across as trivial. I have come across information stating that in Angular, there is no need to unsubscribe from HttpClie ...

Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status. For example: partners = [ 0:{ year: "2022" badge_status: "badge-success" sale_date: "01/07/2022&quo ...

What's the best way to add animation to the send icon while hovering over the button?

<div class="text-center"> <button [disabled]="btnStatus" class="btn btn-secondary buttonSend" type="submit"> <div [hidden]="btnStatus"> Send Message&nbsp;&nbs ...

Angular - Restarting the inactivity redirection feature upon moving to a different page

I've implemented a feature in my Angular app that redirects users to a screensaver page after 30 seconds of inactivity, using code I found here. The functionality works well, but I'm facing an issue where I don't want the redirection to occu ...

leveraging the import statement in conjunction with SystemJs

Currently, I am in the process of creating a sample code using TypeScript and SystemJS for the browser. In my app.ts file: import {Person,add as test} from './testLib' In the generated app.js file (by TypeScript compiler): var testLib_1 = re ...

"Troubleshooting: Issue with component not refreshing in app.component.html

I've been working on setting up the layout of my app in the app.component.html file. One thing I did was create a menu component with its own selector. Here is how my code currently looks: <app-menu></app-menu> <router-outlet>< ...

Checking for GitHub API connectivity issues with GitHub can be done by verifying whether the GitHub API is

Is there a way to check from the GitHub API if it is unable to connect to GitHub or if the internet is not connected? When initializing the API like this: GitHubApi = require("github"); github = new GitHubApi({ version: "3.0.0" ...

Identifying JavaScript Errors in a Web Page: A Guide to Cypress

Currently, I am working on creating a spec file that contains N it(s), with each it visiting a specific page within the application and returning the number of errors/warnings present. I have also shared my query here: https://github.com/cypress-io/cypres ...

Ways to exit a forEach loop when a specific condition is satisfied and obtain a string or break statement

I'm currently using Angular 14 and have been encountering some issues with a piece of code involving a ternary operator. Despite researching resources like this one and others, I haven't found a solution that works for me. The code in question lo ...