How to build a customizable independent (No dependencies) service using Angular 15?

An injection token can be utilized to configure Angular services in a similar fashion. Nonetheless, it currently relies on the Module with Providers methodology for injecting configuration. Are there alternative methods available for configuring services in Angular version 15 without utilizing modules?

Answer №1

It's actually quite simple:

  • supply the token
  • provide the service
  • inject the service

Example:

// defining the token
const token = new InjectionToken<string>('token');

// defining a service that relies on the token 
@Injectable()
export class MyService {
  // injecting the token into the service
  constructor(@Inject(token) private token: string) {}

  getValue(): string {
    return this.token;
  }
}

@Component({
  selector: 'my-app',
  standalone: true,
  providers: [
    // supplying the token & service
    { provide: token, useValue: 'foobar'},
    MyService, 
  ],
  template: ``,
})
export class App {
  constructor(myService: MyService) {
    // enjoy
    console.log(myService.getValue());
  }
}

bootstrapApplication(App);

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

Leverage the power of Filesaver.js in conjunction with Angular

I've searched through all the articles I could find about integrating Filesaver JS with Angular, but I'm still struggling to find a solution that works for me. In my system.config.js file, I included the following code in the map section: ' ...

What is the best way to extract Angular's routing UrlMatchResult from UrlMatcher within a component?

Having trouble with routing in Angular 10. Trying to include a token in my URL that can contain various quantities of / characters. To prevent Angular routing from getting confused, I followed the advice on this post and decided to implement the UrlMatcher ...

Sinon made it difficult to successfully stub/mock a method return

I find myself facing a challenge as I navigate the learning path to nodejs and explore advanced javascript features. Progress is slow but steady. One of the rest endpoints utilizes the (azure blob storage) method from containerclient, which requires conver ...

Enhancing many-to-many relationships with additional fields in Objection.js

I have a question that I haven't been able to find a clear answer to in the objection.js documentation. In my scenario, I have two Models: export class Language extends BaseId { name: string; static tableName = 'Languages'; st ...

What is the solution to the error message Duplicate identifier 'by'?

While conducting a test with the DomSanitizer class, I made some changes and then reverted them using git checkout -- .. However, upon doing so, I encountered a console error: Even after switching to a different git branch, the error persisted. Here are ...

Tips on switching between two divs with a click event in an Angular 4 loop

This question is in reference to the discussion on displaying/hiding dynamic div IDs in Angular2 as seen on Stack Overflow. I have created a Plunker showcasing the issue I am encountering. I am trying to toggle btn1 and btn2 individually within four boxes ...

Tips for concealing a Div element in Angular 4 using webApi

In my Angular 4 web application, I'm looking for a way to display an image if it exists at a certain file location, and if not, I want to show an empty space. Can someone please help me with a solution? Here is my Component.html file: <div cla ...

What is the reason behind the prevalence of using export class xxx in angular4 projects instead of export default class xxx?

Understanding the distinction between export class xxx and export default class xxx is crucial. However, I've noticed that numerous angular4 projects utilize export class xxx in this manner: @Component({ selector: 'call-record', templ ...

How can I export the styling from vite library mode in a React application?

My Vite React TypeScript application features JSX components, module.scss, and global CSS files. Although when I build it in Library Mode, I end up with separate .js, .d.ts, and .css files. However, once I install it in another application, the styling d ...

Assign an appropriate label to this sonarqube input field

Sonarqube flagged an issue with the following line of code: <div class="dropdown-language"> <label>{{'GENERALE.LINGUA' | translate }}</label> <select #langSelect (change)="translate.use(langSe ...

Encountering errors in Angular when trying to access a property that is undefined using

One of the components I've created is being used in its parent component: <app-event-menu-nav [event]="event"></app-event-menu-nav> Below is the code for this component: import {Component, OnInit, ChangeDetectionStrategy, Input} ...

Building Reusable Components in Angular 2: A Step-by-Step Guide

I have implemented a feature in my component where a table can be sorted by clicking on the <th></th> tags. When a user clicks on a th tag, the data is sorted either in ascending (ASC) or descending (DESC) order. In my component, I have set up ...

What is the method in AngularJS2 for using TypeScript to inject dependencies into components?

I have been encountering different methods of injecting dependencies into my component and not all of them seem to be working for me. I am curious about the advantages and disadvantages, what the recommended best practices are, and why some methods are not ...

React | What could be preventing the defaultValue of the input from updating?

I am working with a stateful component that makes a CEP promise to fetch data from post offices. This data is retrieved when the Zip input contains 9 characters - 8 numbers and a '-' - and returns an object with the desired information. Below is ...

Tips for managing promise rejection when generating a highland stream from a promise?

When working with [email protected] and [email protected] via typescript, the following code snippet is utilized: import * as highland from "highland"; import * as lodash from "lodash/fp"; const range = lodash.range(0, 10); const createPromise ...

Angular is failing to show any data on the display, despite there being no apparent errors

As a newcomer to Java and Angular, I am currently enrolled in a course on getting started with Angular. I have been attempting to display information in the navigator, but for some reason, nothing is showing up. Despite thoroughly checking my code, I could ...

React is struggling to locate the specified module

Once I've set up my react project using npx create-react-app called my-app, I proceed to run npm start only to encounter the error shown in the image below. Running node version: 12.16.1 with npm version: 6.13.4 View the error message her ...

Having trouble locating the name 'div' when starting a new React project?

After creating a new React application using the command: "npx create-react-app poi-search --template typescript", ESLint prompted me for permission and then displayed several errors. You can view the screenshot here. I am currently using the latest versi ...

The component is not responding to list scrolling

Issue with Scroll Functionality in Generic List Component On the main page: <ion-header> <app-generic-menu [leftMenu]="'left-menu'" [rightMenu]="'client-menu'" [isSelectionMode]="isSelectio ...

Generic type mapping of TypeScript interface properties

I am struggling to get this to function correctly interface ObjectPool<Ids, T> { pool: { [K in Ids]: T<K>; }; }; interface Player<Id> { id: Id; } let playerPool: ObjectPool<0 | 1 | 2, Player>; in a way that playerPool[0 ...