How to efficiently register services for multiple instances in Angular

Currently, my service includes a field that represents a ViewContainerRef and a method to set the value of this field.

@Injectable({
  providedIn: 'root'
})
export class SomeService {
  public viewContainerRef: ViewContainerRef

  setViewContainer(viewContainerRef: ViewContainerRef) {
    this.viewContainerRef = viewContainerRef
  } 

  //some unique code follows here which relies on the value of viewContainerRef
}

Additionally, I have an abstract base class for each of my components where the SomeService is injected.

export abstract class AppComponentBase {
  viewContainerRef: ViewContainerRef;
  someService: SomeService;

  constructor(injector: Injector){
    this.viewContainerRef = injector.get(ViewContainerRef);
    this.modalService = injector.get(ModalService);

    this.modalService.setViewContainer(this.viewContainerRef);
  }

  //further code not related to the above
}

Furthermore, there are several components in use that inherit the "unique code" from SomeService and extend the AppComponentBase. It's worth noting that multiple inherited instances can exist within the same view.

My main concern is whether after the page is fully loaded and all components are instantiated, will the

this.someService.viewContainerRef
be unique for each component or will it remain the same?

If it turns out to be the same for each, how could I go about making it uniquely assigned?

Answer №1

To ensure that all components are pointing to the same instance of SomeService, inject it in the root so that it becomes a singleton for the application scope. If you require each component to have its own instance, include it in the providers array of the @Component decorator. Visit here for more information on dependency injection in Angular

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

Distinguishing SharePoint React Webpart from Office: A Comparison

My goal is to develop a client-side Webpart in React for SharePoint Online that utilizes OfficeJs to initiate a new email message on the user's Outlook desktop. However, I'm encountering a persistent "Office is not defined" error no matter what ...

What is the method for creating pipes that filter multiple columns?

My pipe is designed to work exclusively for the "name" column and not for the author anymore. transform(items: Book[], filter: Book): any { if (!items || !filter) { return items; } // Filter items array; keep items that match and retu ...

How can I resolve a route error after converting typescript to es5 in an Angular2 example?

I'm currently diving into the world of Angular2 and exploring how to convert TypeScript to ES5. You can find detailed instructions in this documentation: https://angular.io/docs/ts/latest/tutorial/toh-pt5.html Upon running the ES5 code, I encountered ...

Issue encountered during execution of tests involving reactive forms

Having some issues with the code below and looking for a solution. The tests pass when mocking the form for ts tests, but encounter an error when mocking the same form for html: No value accessor for form control with name: 'Enable' If I remov ...

Running nestjs-console commands within an Angular/nx workspace environment can be easily achieved by following these steps

I have integrated a NestJS application within an Angular / Nx workspace environment. For running commands in the Nest application, I am utilizing nestjs-console (e.g., to load fixture data). As per the instructions in the nestjs-console documentation, th ...

Is it possible to export multiple services in an Angular custom library?

After developing a customized library named test-lib, I am able to export TestLibService, TestLibModule, and TestLibComponent using public-api.ts. This allows me to utilize TestLibService from the custom library within an Angular App. The app.module.ts fi ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

Ways to utilize the scan operator for tallying emitted values from a null observable

I'm looking for an observable that will emit a count of how many times void values are emitted. const subject = new Subject<void>(); subject.pipe( scan((acc, curr) => acc + 1, 0) ).subscribe(count => console.log(count)); subject ...

Display a symbol retrieved from the backend server

After receiving a response from the backend server for my Angular 2/4 application, I am presented with an attribute called "connectionStatus". This attribute indicates the status of a database connection, either as "UP" or "DOWN". In order to display this ...

When utilizing a combination of generics in a Typescript mapped type, the resulting property type is not computed

In an attempt to create a versatile method that can handle a Mapped Type named QueryParamObject and partially read its properties: QueryParamObject can handle any type and returns a type where all properties are either string[] or string: export type Quer ...

What is the process for appending an attribute to a DOM element?

Is there a way to conditionally add the multiple attribute to this element? <mat-select [formControlName]="field.name" multiple> I attempted to do so with the following: <mat-select [formControlName]="field.name" [attr.multiple]="field?.mu ...

Closing ngx-bootstrap modal from nested component

I am facing a situation where I need to close the Bs-modal popup after saving data to the database. The saving process is done in the child component, so I passed the Bs-modal to the child component using ()Input. However, I am encountering an issue where ...

What is the best approach to apply type casting in an *ngFor loop for an array containing a variety of types in Angular?

I am facing a scenario where I have two objects named DeviceA and DeviceB, both belonging to the same parent class called Device. interface Device { shared: string } interface DeviceA extends Device { attributeA: string[] } interface DeviceB extends ...

Deliver a distinct service instance for each component

I am facing a scenario where I need to have multiple instances of widget components on the page simultaneously. My goal is to ensure that each instance of the ContainerComponent has its own unique references to service instances. For instance, I aim for e ...

Leveraging subcomponents within a main component in Angular 2

I've structured my Angular2 application with 3 levels of nested components: layout, header, and search. Below is the directory structure: layout/ ├── header/ │ ├── search/ │ │ ├── search.component.ts │ │ ...

mention colleague(parent) instruction request

I have been exploring the use of metadata for setting HTML input attributes. After reading through the Attribute Directives Guide (https://angular.io/docs/ts/latest/guide/attribute-directives.html), I have developed the following implementation: import "r ...

Create a dedicated component to specify the column definition for an Angular Material table

While I have reviewed the documentation on material, I aim to take it a step further with the following customization: wrapper-table.html <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-content>& ...

Import TypeScript files with RequireJS

I'm looking for some clarification on RequireJS. Right now, I compile all my Typescript files into one JS file. If I switch to RequireJS, does that mean I won't have just one JS file anymore? As I understand it, RequireJS dynamically loads JS f ...

Get updates on a new subscription for Angular by signing up now

I have a method for authentication that is kept private. Additionally, I have a public method named login which is utilized in my components to carry out the actual login process. I am interested in subscribing to the login method, which internally subscri ...

What is the best approach to implement a recursive intersection while keeping refactoring in consideration?

I'm currently in the process of refactoring this code snippet to allow for the reuse of the same middleware logic on multiple pages in a type-safe manner. However, I am encountering difficulties when trying to write a typesafe recursive type that can ...