Issue encountered during the attempt to embed one service within another

My latest creation is a service called ContactService.

type contactPredicate = (contact: Contact) => boolean;
type contactLike = Contact | string | SelectedContact;

@Injectable()
export class ContactService {
  private selectedContactId: string = '';
  public selectedContactSubject: BehaviorSubject<contactLike>;

  public get SelectedContact(): contactLike {
    const contact: Contact = this.contactList.find((v) => v.Id === this.selectedContactId);

    return contact ? contact : null;
  }

  public set SelectedContact(value: contactLike) {
    this.selectedContactId = typeof value === 'string' ? value as string : value.Id;
    this.selectedContactSubject.next(this.findContact(this.selectedContactId));
  }

  constructor() {
    this.selectedContactSubject = new BehaviorSubject<Contact>(this.findContact(this.selectedContactId));
  }

}

Inserting this service into another service named "FileService" results in the following code snippet.

import { ContactService } from './contact.service';

@Injectable()
export class FileService {

  constructor(
    private httpServiceProvider: HttpServiceProvider,
    private userService: UserService,
    private contactService: ContactService) {
  }

  // More functionality goes here

}

A SharedModule file showcases the configuration setup for SignalR and other declarations.

// Content of SharedModule.ts

// More code goes here

Details about the AppModule with key components imported such as BrowserModule, CoreModule, and DashboardSharedModule.

// Details from AppModule.ts

// Content goes here

The DashboardSharedModule contains essential components like HeaderComponent, MessageSectionComponent, ConversationSectionComponent, etc.

// Contents inside DashboardSharedModule.ts

// More details included here

An error message related to provider issues between the services has been encountered while arranging both services in the same folder.

PS - Due to clarity purposes, some code snippets have been excluded.

Answer №1

To optimize your architecture, it is recommended to import DashboardSharedModule into AppModule and eliminate the ContactService Provider from AppModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app.routing';

import { AppComponent } from './app.component';
import { CoreModule } from './core/core.module';
import { ContactService } from './dashboard/shared/Services/contact.service';
//DashboardSharedModule IMPORT STATEMENT

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    AppRoutingModule,
    BrowserModule,
    CoreModule,
    DashboardSharedModule//IMPORT HERE
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Optimizing Architecture Practices

The current structure contains a common anti-pattern where a module combines declarations/exports and providers.

A SharedModule should primarily focus on being a widget feature module:

SharedModule typically consists of components, directives, and pipes used universally in the application. This module should mainly contain declarations, with most being exported.

Additionally, SharedModule may re-export other widget modules like CommonModule, FormsModule, and UI control NgModules.

There should be no providers within the SharedModule, as explained earlier. Similarly, neither its imported nor re-exported modules should have providers.

Import the SharedModule into your feature modules, whether loaded during app initiation or lazy loading later on.

On the other hand, CoreModule serves best as a service feature module:

CoreModule usually contains providers for singleton services instantiated at app startup.

Remember to import CoreModule solely in the root AppModule, avoiding its usage in any other module.

Consider designing CoreModule as a clean services module without any additional declarations.

Types of Feature Modules

Learn more about SharedModule and CoreModule.

Answer №2

To eliminate the error, make sure to add the SharedModule to the imports array in your app.module.ts.

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

I am experiencing a strange situation in node.js where the `then` condition of a Promise is not being executed as expected

I am currently troubleshooting a Promise scenario and I am puzzled as to why the second then condition is failing to execute in the setup method. In my app.js code, I can see that the initialize() function is being called and it properly awaits the complet ...

Problem with synchronizing an Angular 2 application and the Angular 2 router

Currently dealing with a complex problem related to asynchronicity within an angular 2 application. The main issue arises when trying to reload information from the backend upon app refresh in the user's browser (such as F5/refresh). The setback occu ...

Using TemplateRef as Custom Component in Angular ng-bootstrap Modal Opening is not Supported

When attempting to use Angular ng-bootstrap Modal open with a custom component passed from a template as a TemplateRef, I encountered some limitations. Initially, my approach was to call the Modal like this: this.modalService.open(ModalWindowComponent, { ...

Adjust the color of the text in Ionic based on the condition

My current solution involves highlighting text in a small slider after a user tap, but it feels very makeshift. <ion-slide *ngFor="let loopValue of values"> <div *ngIf="viewValue == loopValue"> <b> {{loopValue}} </b> ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

How can I prevent an Angular 2+ app from loading until the APP_INITIALIZER has completed its execution?

While I have managed to call a service before the root component loads, I am struggling to find a way to make the whole app wait until the service completes successfully. Essentially, I am looking for a way to make it a synchronous call. The service is loa ...

Retrieving Download URLs from Firestore Storage with AngularFire2 in an Ionic App

As a new developer working on an Ionic project list app with Firestore integration, everything was running smoothly until I reached the point where I needed to add images to my projects. After successfully uploading the picture to Storage and saving the UR ...

Instructions on how to sign up for a worldwide technique that is known as

I have a file called globalvars.ts where I added a global method. How can I subscribe to this method in the ts page where it is being called? globalvars.ts; httpgetmethod(url:string) { var veri; var headers = new Headers(); headers.append(' ...

Developing a custom React Native function for applying 'Title Case' to text

I've been trying to create a function that automatically converts input from users into Title Case. The code I have written seems correct to me, but it's not producing the desired output. It's failing to capitalize the first letter of each w ...

Troubleshooting: Directives in Angular 4 not recognizing RegEx patterns

I have developed a directive that validates the input in a text field, allowing users to enter numbers, dots, and commas. However, the validator only seems to work for numbers and not for commas and dots. import { Directive, ElementRef, HostListener } fro ...

What are the properties needed for a context provider around the component <App/>?

Let's take a look at how I've set up a context provider to wrap my <App/> component: // index.ts ReactDOM.render( <ApolloProvider client={client}> <React.StrictMode> <AuthProvider> <App /> & ...

Enhance your coding experience with TypeScript's autocomplete in Visual Studio Code

After migrating a project from JavaScript to TypeScript, I am not seeing autocomplete suggestions or type hints when hovering over variables in Visual Studio Code editor (Version 1.7.2). Even the basic example provided below does not display any auto-com ...

Example of binding a popup to a geoJSON feature

Currently, I have successfully overlayed geojson data on a map, but I would like to enhance the user experience by allowing them to click on an area and view detailed information in a popup. I tried using the example provided on Leaflet's website: L.g ...

Can you identify a specific portion within an array?

Apologies for the poorly titled post; summarizing my query into one sentence was challenging. I'm including the current code I have, as I believe it should be easy to understand. // Constants that define columns const columns = ["a", " ...

I can't seem to figure out the issue with ngOnit, it

Tried various solutions but still unable to resolve this error. The error I'm encountering is "ngonit is missing in type 'homeController'". Any assistance would be greatly appreciated. import { Component, OnInit, ViewEncapsulation } from & ...

Missing index.html in the ./dist folder following the production build of Angular 8 Universal

After upgrading Angular 7.0 to 8.2.5 in my SSR app, everything seems fine except for the production build. The main issue is that the index.html file is missing in the "./dist/browser" directory. I am running the build using the following command: ng buil ...

Issue: Oops! The digital envelope routines are not supported in Angular while attempting to run the project

I encountered an error when running the command below: ng s The error message is as follows: Error: error:0308010C:digital envelope routines::unsupportedat new Hash (node:internal/crypto/hash:68:19)at Object.createHash (node:crypto:138:10)at BulkUpdateDe ...

Currently attempting to ensure the type safety of my bespoke event system within UnityTiny

Currently, I am developing an event system within Unity Tiny as the built-in framework's functionality is quite limited. While I have managed to get it up and running, I now aim to enhance its user-friendliness for my team members. In this endeavor, I ...

Issue with Ionic 3 modal: Navparams coming back as undefined

I'm currently facing an issue where I am passing a string as a parameter to a Modal (specifically a master/detail modal) and although the Modal opens successfully, the string is being returned as undefined. Below is the TypeScript code for the parent ...

A guide on connecting multiple select components to a unified Angular 6+ reactive form without triggering redundant updates

I am facing an issue where I need to connect multiple input components to a single angular reactive form, but encounter two main obstacles: By default, only the form in which user input occurs gets updated If I use [(ngModel)] it does work, but it trigge ...