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