网站搜索

TypeScript - Angular中的依赖注入


我刚接触 Angular,我已有一个功能正常的后端(用 c# asp.net 编写),我想使用 Angular 来做前端。我一直在跟一些不错的教程,但它们中的许多都使用了虚拟后端。

我知道在 Angular 中依赖注入是好的实践,我在我的代码中也使用了一些,但现在我正在调用后端来创建一个用户,我想知道我是否应该使用依赖注入来创建我想在 POST 请求中作为主体发送的对象(如果是的话,我应该如何做),或者我是否可以像现在代码中那样保持不变。

我的代码正在使用 Angular 7 运行。

这是我的班级:

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

我通过依赖注入使用的服务来调用我的 web 服务:

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

这就是我如何调用我的服务,以及我在哪里问自己是否应该保持这种方式,或者是否应该使用依赖注入:

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

代码运行正常,但我希望现在就尽可能完美地完成它!

感谢你的回复/阅读/建议,祝你有美好的一天!

利奥

答案#1

将 FormGroup 转换为模型时:

Object.assign(YourVariable, this.YoutFormName.value);

答案#2

就你的 user 变量而言:
你主要将依赖注入用于服务或“实际类”。你的类 UserRegister 更像是一个数据传输对象(DTO),本身不提供任何逻辑。但关键是,如果你需要非可注入的构造函数参数,DI 会变得有些不方便。有一些解决方法,例如在注入后使用一个“Initialize”方法,但我认为在你的情况下,不使用 DI 是更合适的方式。