What is the process for calling subjects dynamically in a service?

Do you have a service with the following subjects?

  subjectOne$ = new Subject<Partial<boolean>>();
  subjectTwo$ = new Subject<Partial<boolean>>();
  subjectThree$ = new Subject<Partial<boolean>>();
  subjectFour$ = new Subject<Partial<boolean>>();

If so, how can you dynamically call them from the component?

onToggle(number: string) {
    this.myService.subjectOne$.next(this.selected[number]);
  }

You mentioned doing the param inside next() but are unsure of how to call subjectXXXX$ dynamically. Any ideas on how to achieve that?

Answer №1

One approach could be to store subjects in a map and access them dynamically.

subjectMaps: {[key: string]: Subject<Partial<boolean>>} = {
    one : new Subject<Partial<boolean>>(),
    two : new Subject<Partial<boolean>>(),
    three: new Subject<Partial<boolean>>(),
    four : new Subject<Partial<boolean>>()
  }

To make accessing easier, create a service function that retrieves the subject by key:

subjectByKey(subjectKey: string): Subject<Partial<boolean>> {
    return this.subjectMaps[subjectKey];
  }

Then, call this function from your component like so:

onToggle(number: string) {
    this.myService.subjectByKey('one').next(this.selected[number]);
  }

Answer №2

The question is a bit confusing to me, but I believe utilizing an object for the subjects could be a viable solution.

subjects = {
  1: new Subject<Partial<boolean>>(),
  2: new Subject<Partial<boolean>>(),
  ....
}

onToggle(number: string) {
    this.myService.subjects[number].next(/* insert desired value */);
  }

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

Determine the Variable Type by Evaluating the Value of Another Variable

I am looking to implement the following functionality: document("post").insert({ ... } /* TYPE SHOULD BE AUTOMATICALLY DETERMINED BY TYPESCRIPT */ ); The document() function returns an object that includes methods like insert. The returned objec ...

Using Ionic 2 to fetch JSON data and display it using ngFor

My script.php generates a JSON array with data from mySQL; The next step involves retrieving this JSON array via AJAX; I am looking to dynamically create divs using ngFor, but I'm unsure of how to handle the callback for the JSON array in the Ajax s ...

Arranging information within the Ngb-Accordion

Welcome to the code snippet showcasing how to create an accordion in Angular: <ngb-accordion [closeOthers]="false" activeIds="0"> <ng-container class="card" *ngFor="let post of Posts"> <ngb-panel title="{{post.title}} - ...

Mastering the Proper Use of Bootstrap-Tagsinput in Angular2

I have been trying to incorporate the bootstrap-tagsinput library into my Angular2 project. I successfully installed the library using the package.json file: "dependencies": { ... "bootstrap-tagsinput": "^0.7.1", ... } After installation, ...

When attempting to update a document using the PUT method in the MEAN stack, no changes are being applied

My application is designed to perform CRUD operations, it's very simple. I'm trying to update the information of a book but it's not working. What should I change? Additionally, I'm encountering this error: core.js:6210 ERROR TypeError ...

To utilize the range-datepicker package, make sure to first include it in your package.json

Seeking assistance with a potential issue I am facing, hoping for a simple solution. I am currently working on an Angular4 project and would like to incorporate this component. https://www.npmjs.com/package/range-datepicker After attempting to integrate ...

Encountering issues with Proxy functionality in the latest versions of Angular 13 and Spring Boot

I've encountered an issue with the proxy configuration in Angular. I'm unsure if it's a problem within my Angular settings or if there's a configuration issue in Spring. For testing purposes, I have a backend built in springboot to han ...

Guide on utilizing jasmine's spy functionalityAlways remember to use the

I am a beginner when it comes to Angular and Jasmine, and I am encountering difficulties while attempting to mock: public uploadFile(confirm) { this.uploadModalRef.close(); if (this.filePath.length) { let ngbModalOptions: NgbModalOptions = { ...

Angular 5 arrays within arrays

I'm currently facing an issue with using ngFor on a nested JSON output. The outer loop is working as expected, but the inner loop is not functioning properly. Below is my code snippet: Typescript file import { Component, OnInit } from '@angula ...

Customize specific styles for individual divs one at a time (without the use of jQuery)

Can you assist me with this issue? I am trying to display the <span class="badge badge-light"><i class="fa fa-check-circle"></i></span> tag (initially set to "visibility: hidden") when clicking on a div with the class "role-box". He ...

The JSX component cannot be 'FieldArray' at this time

I'm working on a next.js project and using the Formik component. However, I encountered a type error that says "'FieldArray' cannot be used as a JSX component." Can anyone help me resolve this issue? Here is the error message: 'FieldAr ...

Utilizing indexing for list data presentation in Angular instead of relying on property names

I need help with displaying data from a list retrieved from a database without having to specify the property names. I want to create reusable Markup for this purpose. Below is my current code snippet: <div class="card card-design" *ngFor="let val of l ...

Angular/Typescript: develop a factory function that creates objects based on the parent class's properties

I'm currently working on implementing a factory method that can return classes dynamically, and here's my code snippet: getWidget<T extends WidgetBase>(componentName: string): Type<T> { switch (componentName) { default: ...

Learn how to bring a component into another component within Angular

I have developed a component named CopySchedulefromSiteComponent and now I am looking to import it into another component called SiteScheduleComponent. However, I am unsure of the correct way to do this. The CopySchedulefromSiteComponent contains one fiel ...

Updating the data and processing results settings for Select2 in an Angular 2 application

In my Angular2 app, I am utilizing Select2 and facing a challenge with accessing class properties in the data and processResults contexts. Unfortunately, these contexts do not belong to the class: export class DefaultFormInputSelectComponent { @Input ...

Securing pathways in Next.js using middleware and Next-Auth

Hey there, I'm currently working on adding some route protection in NextJS using middleware for authentication with next-auth. According to the documentation, this is what my middleware.ts file should look like: export { default } from "next-auth ...

Convert the XML response from an API into JSON

Is there a way to convert my XML response into JSON using Angular? This is the response I am working with: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt; &lt;Fer ...

Refreshing data with Angular 2 Observables

I am currently facing an issue with refreshing my table in the parent component after performing an update operation in the child component. @service getLicenses(){ ... return this.http.post(url:"", options) .map((result: Response) => ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...

What are the various methods for configuring an Angular application within Eclipse?

I am new to using Angular and I am eager to learn the different ways in which I can create an Angular application in Eclipse. Some sources suggest installing the Angular IDE, while others mention the following: Tools and Prerequisites Node.js and NPM ...