Angular 2's one-of-a-kind singleton solution

I'm feeling a bit lost when it comes to singleton services in Angular 2. I need a translation service that will be accessible throughout the entire application, and I want to ensure that only one instance of the service exists. My issue arises when trying to implement two language switch buttons. While my content translation works fine using a pipe, the switch buttons throw an error message:

'self.parent.context.use is not a function'.

I believe this error stems from a misunderstanding of certain Angular concepts. Can someone provide guidance on how to correctly implement a global service?

//Translation service
@Injectable()
export class TranslateService {
  private _currentLang: string;

  constructor(){
    this._currentLang = 'es';
  }

  public get currentLang() {
    return this._currentLang;
  }

  public use(lang: string): void {
    // set current language
    this._currentLang = lang;
  }

  private translate(obj : LocalizedData): string {
    // perform translation privately
    return obj[this._currentLang];
  }

  public instant(obj: LocalizedData ) {
    // call translation
    return this.translate(obj); 
  }
}

//Navbar Module
@NgModule({
  imports:      [ CommonModule, FormsModule],
  declarations: [ NavbarMenuComponent, TranslatePipe],
  exports: [ NavbarMenuComponent]
})

export class NavbarModule { }

//App component
@Component({
  selector: 'app',
  template:'<navbar-menu ></navbar-menu>'
})

export class AppComponent implements OnInit{
  public translatedText : string;
    constructor(){}
    ngOnInit(){}
  }

//app Module
@NgModule({
  imports:      [ BrowserModule, FormsModule, NavbarModule],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent],
  providers: [ TranslateService],
})

export class AppModule { }


//Main
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule,[ TranslateService]);
 

Answer №1

Angular2 follows the singleton pattern for services per provider, meaning if you provide a service multiple times, you'll end up with multiple instances.

However, when you provide a service within

@NgModule({ 
  providers: [SomeService]
  ...
})

it is provided at the root scope of the application, resulting in a single instance for the entire application. Even if multiple @NgModule() include the same service in their providers, only one instance will be created as they are all defined at the application root scope.

Each lazy loaded module has its own root scope separate from the main application.

On the other hand, providing a service within @Component() results in each component instance and its children having a unique service instance.

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

Testing the derived class resulted in failure with the error message: "Unable to resolve all parameters for : (?, ?) in Angular 5."

Encountering an issue when trying to run Karma on a structure consisting of an abstract class, a derived class, and a test. The error message that is being thrown is: Failed: Can't resolve all parameters for ActivationsComponent: (?, ?). The abstrac ...

Using Angular 2 to Toggle a Checkbox when a Div is Clicked

Whenever a user clicks on a unit div, I want to target the checkbox and mark it as checked/unchecked. I also want to apply the class unit-selected if the checkbox is checked, and remove the class unit-selected if the checkbox is unchecked. I have tried lo ...

Observing rxjs Observable - loop through the results and exit when a certain condition is met / encountering an issue with reading property 'subscribe' of an undefined value

I'm fairly new to working with rxjs and I've been struggling to find the right operator for what I want to achieve. Here's my scenario - I have an array that needs to be populated with results from another observable. Once this array has en ...

The CLI variation is exclusively designed to work with Angular versions starting from 14.0.0 up

I encountered the following issue: This CLI version is designed to work with Angular versions ^14.0.0, however, I have Angular version 15.0.0 installed. For instructions on updating Angular, please visit: https://update.angular.io/ Even after updating An ...

Trigger @HostListener event after a certain delay

I am currently working on implementing a basic infinite-scroll directive in Angular2. To achieve this, I am utilizing @HostListener('window:scroll') to capture the scroll event and extract the data from the $target. My concern is that every time ...

NgFor conditional slice pipe

Is there a way to conditionally slice the output in an ngFor loop? Take a look at the snippet of HTML template below: <div *ngFor="let bucket of getBucketsWithValues(bucketName.criterium ? bucketName.criterium : bucketName) | orderBy:'key' ...

Learn the art of bypassing TypeScript errors using @ts-ignore!

I recently encountered an issue when trying to import a pure JavaScript library into a TypeScript project, resulting in the error message: Could not find a declaration file for module xxx. After some research, I learned that this error can be suppressed u ...

`How can I incorporate typography into my Angular Material design?`

For my angular app, I am developing a custom theme and incorporating bootstrap's reboot to establish a basic starting point for non-material elements. To avoid conflicts with material variables, I converted the reboot into a mixin. In this mixin, I pa ...

Rendering HTML content in a preformatted <code> tag using Electron

Recently, a brand new electron/angular application was built with the code snippet running in main.ts: win.loadURL(url.format({ pathname: path.join(__dirname, 'dist/index.html'), protocol: 'file:', slashes: true })); After launc ...

The Vite proxy server will not modify POST requests

When I set up a proxy using Vite, I noticed that it only handles GET and HEAD requests. I'm looking to have other request methods proxied as well. In a new Vite React project - the only modification I made was in vite.config.ts import { defineConfig ...

Unable to create resource in nestjs due to typeScript compatibility issue

Encountered an Error: TypeError: Cannot access 'properties' property of undefined Failed to execute command: node @nestjs/schematics:resource --name=post --no-dry-run --language="ts" --sourceRoot="src" --spec Attempts made ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

Pattern matching to exclude specific characters

To enhance security measures, I am looking to restrict users from inputting the following characters: ~ " # % & * : < > ? / \ { | } . The key requirement is that all other characters should be permitted, while ensuring that only the sp ...

Conditionals in Angular 2 using Sass

Looking to apply this style with Sass or CSS: IF :host.form-control MATCHES .ng-valid[required] OR .ng-valid.required THEN :host ::ng-deep input.form-control = border-left: 5px solid #42A948; Appreciate the help! ...

What is the best way to display data retrieved through an HTTP service using ngFor?

I was attempting to inject a service (contact.service.ts) into a component (contact-list.component). The service contains data on employees defined in contacts.ts. While I was able to successfully receive the data, I encountered difficulty in rendering it ...

Check out the computed typescript types

In my work with TypeScript types, I find myself frequently using Omit, Pick, and similar tools based on other types. While it generally gets the job done, I often struggle with readability when dealing with complex type manipulations. I am interested in f ...

`The dilemma of z-index in a dropdown menu nested within an animated card`

Having an issue that I have attempted to simplify in this StackBlitz example (the actual project is created with Angular components and Bootstrap, etc.): https://stackblitz.com/edit/angular-bootstrap-4-starter-njixcw When incorporating a dropdown within ...

Enhance the performance of your React/NextJS app by controlling the rendering of a component and focusing on updating

I'm facing an issue with my NextJS application that showcases a list of audio tracks using an <AudioTrackEntry> component. This component receives props like the Track Title and a Link to the audio file from an external data source. Within the ...

Error message: "Supabase connection is returning an undefined value

I am encountering an issue with my Vercel deployed Remix project that utilizes Supabase on the backend, Postgresql, and Prisma as the ORM. Despite setting up connection pooling and a direct connection to Supabase, I keep receiving the following error whene ...

Detecting the presence of a session in Angular2 and nodejs using express

My server-side session creation is functioning properly, but I need to be able to hide certain elements in an Angular2 component template depending on whether the session exists. How can I check within my Angular2 component whether the server-created sessi ...