Can you retrieve the Angular Service Instance beyond the scope of an angular component?

Is it possible to obtain the reference of an Injectable Angular service within a generic class without including it in the constructor? I am exploring different methods to access the Service reference.

For example:

export class Utils {
  getData(): string {
      //Get Service reference without constructor
      if(!isAuthorized()) return

     //Do something
  }
}



@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  isAuthorized(): boolean {
      //Perform actions
   }
}

Answer №1

From Angular 14 onwards, the inject(..) function can now be utilized in a broader range of scenarios, although still with some limitations:


export class Utils {
  authenticationService = inject(AuthenticationService);

  getData(): string {
    if(!authenticationService.isAuthorized()) return;

    //Carry out a specific task
  }
}

https://angular.io/api/core/inject#usage-notes

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

Bringing in External Components/Functions using Webpack Module Federation

Currently, we are experimenting with the react webpack module federation for a proof of concept project. However, we have encountered an error when utilizing tsx files instead of js files as shown in the examples provided by the module federation team. We ...

Issue: Loading ES Module in MikroOrm and Typescript requires the use of import statement

My attempt to set up a mikrorm configuration for my postgres DB is hitting a snag when I try to run my run-dev script. The issue stems from an ESM compilation error: > yarn dev Error: Must use import to load ES Module: C:\Users\Itay&b ...

The element is implicitly assigned the 'any' type due to the inability to use an expression of type to index the element

Check out my TS playground here // I have colours const colors = { Red: "Red", Blue: "Blue", Green: "Green" } type TColor = keyof typeof colors; // Some colours have moods associated with them const colorsToMood = { ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...

Oops! Looks like there was an error trying to assign the value "$event" to the template variable "element". Remember, template variables can only be read

Can anyone assist me in identifying the issue with this code? <div *ngFor="let element of list; let index=index"> <mat-form-field> <input matInput type="string" [(ngModel)]="element" name="element ...

Tips for showing errors in a FormGroup within Angular 8

My website features a textarea that must be filled out with at least 10 characters before the user can submit it. If these requirements are not met, I want to show an error message. Below is the HTML code: <form [formGroup]="formGrp" (submit)="onSubmi ...

Error message: "The toJSON method is not found for the item in the nested array of

Encountering an issue with NSwag in my Angular project where it throws an error when attempting to send data if the object contains a nested array of objects like this: export interface IJobAdDto { mainJobAd: JobAddDetailsDto; differentLanguageJobA ...

Post-upgrade to .Net Core 3.1, the Liveness and Readiness probe encountered failures

Recently, I updated my .Net Core from version 2.1 to 3.1. However, after the upgrade, the Liveness and Readiness probe to the pods failed. Below is an excerpt from my docker file: FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base WORKDIR / ...

Is it possible to integrate Angular 2 with Thymeleaf in a single application?

I'm trying to combine Thymeleaf th: with Angular2 templates, but I'm having trouble getting them to compile together. Is there a way to make them work simultaneously? import {Component, NgModule} from '@angular/core' import {BrowserMod ...

Karma Test Error: Disconnected due to lack of communication within a 60000 millisecond timeframe

Executing the "ng test" command for Unit Testing in an Angular project is resulting in some errors. Chrome Headless 120.0.6099.130 (Windows 10) ERROR Disconnected , because no message in 60000 ms. Chrome Headless 120.0.6099.130 (Windows 10): Executed 404 ...

Attempting to assign the object retrieved from the interface as the new value for window.location.href

I encountered an issue where the error message Type MyInterface' is not assignable to type 'string' popped up. Although I comprehend the problem, finding a suitable solution has proven to be challenging. MyInterface solely returns one item, ...

Evolution of fontawesome icon designs

When utilizing font awesome icons in my angular code, the implementation looks like this: component.ts: import { faSquare } from '@fortawesome/free-solid-svg-icons'; faSquare =faSquare; html: <fa-icon [icon]="faSquare"</fa-icon ...

Encountering an Error: Unforeseen Token < Causing Webpack Configuration Problem in Typescript

Seeking assistance to resolve an issue that has arisen while working on a project with Typescript, React, and Webpack. I referred to the guide available at https://www.typescriptlang.org/docs/handbook/react-&-webpack.html After configuring everything, ...

Error in AngularFire2 typings: The property 'take' is not present in the type 'FirebaseObjectObservable<any>'

Recently, I upgraded my ionic app from beta 11 to rc0, which also involved transitioning from typescript 1.8 to version 2. After following the configuration steps for AngularFire2 on the site Getting Started with Ionic 2 RC0, Firebase 3 + AngularFire 2, I ...

How can I set up a KeyboardEvent listener in JavaScript?

My attempt to use @keydown resulted in an error: Type 'Event | KeyboardEvent' is not assignable to type 'KeyboardEvent'. Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, c ...

How to Modify CSS in Angular 6 for Another Element in ngFor Loop Using Renderer2

I have utilized ngFor to add columns to a table. When a user clicks on a <td>, it triggers a Dialog box to open and return certain values. Using Renderer2, I change the background-color of the selected <td>. Now, based on these returned values, ...

Extending the Model class in TypeScript with Sequelize

Currently, I am tackling a legacy project with the goal of transitioning it to Typescript. The project contains models that are structured as shown below: import Sequelize from "sequelize"; class MyModel extends Sequelize.Model { public static init(seq ...

Chrome stack router outlet and the utilization of the Angular back button

I'm experiencing an issue with the back button on Chrome while using Angular 14. When I return to a previous page (URL), instead of deleting the current page components, it keeps adding more and more as I continue to press the back button (the deeper ...

What is the process for obtaining a flattened tuple type from a tuple comprised of nested tuples?

Suppose I have a tuple comprised of additional tuples: type Data = [[3,5,7], [4,9], [0,1,10,9]]; I am looking to develop a utility type called Merge<T> in such a way that Merge<Data> outputs: type MergedData = Merge<Data>; // type Merged ...