英文:
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: '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}`),
}
}
This will prevent re-creating namespaces or any objects for every client use.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论