2

I'm new in Angular, I have a back-end already functional (written in c# asp.net), and I wanted to do a front-end using angular. I've been following some good tutorials but many of them used a fake back-end.

I know that dependency injection is good practice in angular, I have some of it in my code, but right now I'm calling my back-end for creating an user and I was wondering if I should use dependency injection to create the object that I want to send as body in my POST request (and if, how should I do this) or if I can leave it as it is in my code right now.

My code is running with Angular 7.

Here is my class :

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;
}
}  `

My service that I use via dependency Injection to call my webServices :

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));
 }

public create(route: string, body) {
return this.http.post(this.createCompleteRoute(route, this.envUrl.urlAddress), body, this.generateHeaders());
}

public update(route: string, body) {
return this.http.put(this.createCompleteRoute(route, this.envUrl.urlAddress), body, this.generateHeaders());
 }

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

private createCompleteRoute(route: string, envAddress: string) {
return `${envAddress}/${route}`;
}

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

And here is how I call my service and where I ask myself if I should keep it that way or if I should use Dependecy Injection :

onSubmit() {
this.submitted = true;

// stop here if form is invalid
if (this.registerForm.invalid) {
  return;
}
this.loading = true;
//Should I keep it like that?
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;
    });
 }

The code is working as expected but I would like to do it as perfectly as possible already now !

Thanks for the responses/reading/advices, have a nice day !

Lio

6
  • 2
    For working code you should probably post on Code Review Commented May 7, 2019 at 13:40
  • 2
    Can you show me how you initialize your repo variable ? You use this.repo, I'm pretty sure you already use DI Commented May 7, 2019 at 14:05
  • import { RepositoryService } from '../shared/services/repository.service' @Component({ templateUrl: 'register.component.html' }) export class RegisterComponent implements OnInit { registerForm: FormGroup; loading = false; submitted = false; constructor( private formBuilder: FormBuilder, private router: Router, private repo: RepositoryService, private alertService: AlertService ) { } Commented May 7, 2019 at 14:53
  • repo is the repositoryService and yes with it I use DI, but I was wondering if I should use DI when I initialize my user variable Commented May 7, 2019 at 14:55
  • 1
    @lioleveau I'm not sure why you want to use DI for your user variable. Maybe you misunderstand what's the purpose of using DI ? Please, read the the quick explanation provided by Angular about Dependecy Injection in the fundamental architecture guide. It might help you ! Commented May 7, 2019 at 15:23

3 Answers 3

2

For casting FormGroup into Model:

Object.assign(YourVariable, this.YoutFormName.value);
Sign up to request clarification or add additional context in comments.

Comments

1

As far as your user variable is concerned:
You use dependency injection mainly for services or 'actual classes'. Your class UserRegister is more of a data transfer object (DTO) and provides no logic of its own. But the important part is that DI gets somewhat ugly if you have the need for non injectable constructor parameters. There are ways around this, i.e. by using an 'Initialize' method after its injection, but I think in your case, not using DI is the preferred way.

2 Comments

Thanks for your response, that's all I wanted to know, have a nice day !
Glad to help. If you don't mind you could do me the honor of getting my first accepted answer.
1

Best practice is to always use DI within the context of Angular. It's baked into the structure.

https://angular.io/guide/dependency-injection

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.