将命名空间添加到Angular服务

huangapple go评论62阅读模式
英文:

Add namespaces into Angular service

问题

I understand your request. Here is the translated content:

我有一个使用 Angular v16 的网页客户端,它有一个非常零散的 API 服务,每个数据库实体有大约 10 个不同的调用,例如:

  • addUser
  • deleteUser
  • updateUser
  • 等等... 还有很多其他东西

...然后每个数据实体都有 20 倍的调用。

我想以某种方式进行重构,使用命名空间,这样客户端可以像这样开始使用它:

constructor(private api: ApiService) {
    this.api.user.add(params);
}

今天有没有推荐的实现方法?或者至少有什么是实现这个的好方法吗?

英文:

I have a web client in Angular v16, which has a very fragmented API service, with about 10 different calls for each of 20 database entities, like this:

  • addUser
  • deleteUser
  • updateUser
  • etc... many other things

...and then 20 times that, for each data entity.

I want to refactor it somehow, into namespaces, so clients can start using it like this:

constructor(private api: ApiService) {
    this.api.user.add(params);
}

Is there a recommended approach to implementing this today? Or at least what would be a good way to implement this?

答案1

得分: 1

由于Angular中的服务是单例的,我发现将命名空间组织为服务内的readonly对象是最佳方式:

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {
  }

  readonly users = {
     all: () => this.http.get<IUser[]>(`api/users/all`),
     get: (userId: string) => this.http.get<IUser>(`api/user/${userId}`),
     add: (user: IUser) => this.http.put<string>(`api/user`, user),
     update: (user: IUser) => this.http.patch(`api/user`, user),
     delete: (id: string) => this.http.delete(`api/user/${id}`),
  }

}

这样可以防止为每个客户端使用重新创建命名空间或任何对象。

英文:

Since services in Angular are singletons, I found that the best way is to organize namespaces as readonly objects inside the service:

@Injectable({
  providedIn: &#39;root&#39;
})
export class ApiService {
  constructor(private http: HttpClient) {
  }

  readonly users = {
     all: () =&gt; this.http.get&lt;IUser[]&gt;(`api/users/all`),
     get: (userId: string) =&gt; this.http.get&lt;IUser&gt;(`api/user/${userId}`),
     add: (user: IUser) =&gt; this.http.put&lt;string&gt;(`api/user`, user),
     update: (user: IUser) =&gt; this.http.patch(`api/user`, user),
     delete: (id: string) =&gt; this.http.delete(`api/user/${id}`),
  }

}

This will prevent re-creating namespaces or any objects for every client use.

huangapple
  • 本文由 发表于 2023年5月20日 22:31:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定