Angular's Dependency Injection Essentials

As a newcomer to Angular, I have successfully developed a backend using C# ASP.NET and now I'm looking to create a frontend in Angular. While following tutorials, I noticed that many of them use a fake backend for demonstration purposes.

I understand the importance of dependency injection in Angular and have implemented some in my code. However, I am currently calling my backend to create a user and I am considering whether I should use dependency injection to create the object that will be sent as the body in my POST request. If so, how should I go about implementing this in my Angular 7 code?

Below is a snippet of the user registration class in my code:

export class UserRegister {  

username: string;
password: string;  
Email: string;  
town: string;
fiability: number;
nbEventsParticipated: number;
nbEventRegistered: number;

constructor(userN: string, pass: string, email: string, location: string) {
this.username = userN;
this.password = pass;
this.Email = email;
this.town = location;
}
}  `

The repository service I utilize for calling web services via dependency Injection is shown below:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { EnvironmentUrlService } from './environment-url.service';

@Injectable()
export class RepositoryService {

constructor(private http: HttpClient, private envUrl: EnvironmentUrlService) { }

public getData(route: string) {
return this.http.get(this.createCompleteRoute(route, this.envUrl.urlAddress));
 }

// Other methods omitted for brevity

private generateHeaders() {
return {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}
}
}

In the following snippet, I showcase how I currently call my service and question whether I should stick with this approach or incorporate Dependency Injection:

onSubmit() {
this.submitted = true;

if (this.registerForm.invalid) {
  return;
}
this.loading = true;

let user: UserRegister = new UserRegister(this.f.username.value, this.f.password.value, this.f.mail.value, this.f.town.value);
let body = JSON.stringify(user);   
localStorage.removeItem('currentUserJWT');
this.repo.create('api/Login/CreateProfil', body)
  .subscribe(res => {
    alert(res);
    this.router.navigate(['/login']);
  },
    error => {
      this.alertService.error(error);
      this.loading = false;
    });
 }

Although the current code functions correctly, I aim to optimize it further. Any suggestions, advice, or feedback would be greatly appreciated. Thank you!

Lio

Answer â„–1

To convert a FormGroup into a Model, you can use the following code:

Object.assign(MyObject, this.MyForm.value);

Answer â„–2

Regarding the user variable in question:
Dependency injection is typically utilized for services or 'concrete classes'. In your scenario, the class UserRegister functions more as a data transfer object (DTO) without any inherent logic. However, dependency injection can become cumbersome if non-injectable constructor parameters are required. While workarounds like an 'Initialize' method post-injection exist, it may be advisable to forego DI in this particular case.

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

What is the reason behind the inability to access a static member in a property method, but being able to access it

Why is it an issue to access a static member from a property method in TypeScript? This behavior works fine in plain ES6 and as a proper prototype method. class FooBar { static v = 123; static foo = () => this.v; // this throws an error in TS ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

What is the process for defining a recursive array data structure?

Looking to implement a TypeScript method that can navigate through nested arrays of strings when given an instance of a type/class/interface. The method, in concept, should resemble: method<T>(instance: T, arrayAttr: someType) { let tmp = undefin ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

Issue with importing Typescript and Jquery - $ function not recognized

Currently, I am utilizing TypeScript along with jQuery in my project, however, I keep encountering the following error: Uncaught TypeError: $ is not a function Has anyone come across this issue before? The process involves compiling TypeScript to ES20 ...

Using Angular's setTimeout() function with an external lambda that includes a parameter

My goal is to tackle two issues at once: 1) using setTimeout( #action#, timeMillis) with #action# as a lambda 2) supplying the lambda with a parameter. The common method of setTimeout( ()=>{ #callback# }, timeMillis) works flawlessly when extracting () ...

I successfully created a basic application using Ionic and Angular. Is there a way to generate an APK file with Capacitor without relying on Android Studio?

Is it feasible to create an apk file in Ionic without relying on Android Studio? If so, what is the process for doing that using only Capacitor? ...

Tips for integrating Angular Material styles into Sonarque

Can Sonarqube analyze my Angular application prominently using Angular Material? The styling I have is: .some-class { mat-icon { color: red; } } Since Angular Material is globally added through angular.json configuration, So ...

Switching the location of the PrimeNG Doughnut Label to the left side using Angular version 14.2.12

I’ve been struggling to position the labels of my Doughnut chart on the left side, but I just can't seem to make it work. Here is the configuration I've tried: this.options = { legend: { position: 'left', align: ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...

The transformative power of Firebase snapshot updates in Angular 2

Currently experiencing an issue with Firebase and Angular 2. I have a system where users can apply to various tasks. loadTask() { let post = [] const publicationRef = this.rootRef.child('task').child('attente'); const usersR = th ...

Integrating Auth0-js with the usePostMessage functionality

Encountering difficulties when compiling an Angular application that incorporates the auth0-js package. The code utilizes the method renewAuth(options: RenewAuthOptions, callback: Auth0Callback<any>): void;, yet it seems to be causing issues as the p ...

Tips for handling mismatched function parameters in TypeScript when using an unspecified data type

Even though I wish it wasn't the case, TypeScript accepts the code below in strict mode. The function's value argument is defined as either an unknown or an any type, meaning it can be anything at this point as it is being passed along. However, ...

Centering on request, Google Maps adjusts its view to focus on

When I select a row, I want to set the map center to the provided coordinates in Primeng. The issue is that while this.options works fine in ngOnInit, it doesn't work when called in the showCords() function. Below is my code: gmap.component.ts im ...

Locate and refine the pipeline for converting all elements of an array into JSON format using Angular 2

I am currently working on implementing a search functionality using a custom pipe in Angular. The goal is to be able to search through all strings or columns in a received JSON or array of objects and update the table accordingly. Here is the code snippet ...

Utilize restrictions (type/interface) on data types

When working with TypeScript, I am creating a type that consists of unions of other types: type A = B | C | D // ... One important requirement is that I want to ensure at compile time that B, C, D, and so on, have the structure of a generic template to en ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

The custom classes do not work with the ngx-bootstrap modal feature

I'm in the process of setting a new width for a modal that has been created using BsModalService. I have found that I can't change it by assigning a custom class, but only by utilizing the given classes like 'modal-xl'. Can you explain ...

Is there a way to automatically determine the parameters of a constructor to match the default class type in TypeScript

I need a function in a class that can utilize a type from constructor arguments, but I am unsure how to achieve this. class CustomClass<Type1, Type2=any>{ a: string = 'a' constructor(private readonly parameters: { attributes: Type ...

Utilizing React with Typescript to create JSX text translation files

My task involves translating text stored in a file... ///translations.txt const TEXT: { [x: string]: { [y: string]: string } } = { en: { joinNow: <React.Fragment>Join <b>Now<b/></React.Fragment>, signUp: <React.Fragmen ...