我正在开发一个角度应用程序。假设当我们实现某个按钮的 onclick 等功能时,调用 api,处理数据,在表中显示结果。表数据应该跨页面保留(因此我们需要保持变量处于服务状态)。
为了实现,首先我们可以开始从模板调用函数,然后在组件中我们可以做一些检查,并调用服务来获取数据。一旦我们得到了数据,如果我们想要处理数据,那么处理数据的函数应该在组件或服务中?
我们可以在服务文件中编写逻辑吗?或者它应该在组件文件中?最佳做法是什么?
方法一:
getApi() {
this.http
.get(url)
.subscribe(response=> {
this.afterFetchingProcessData(response); // this might be some function in service file
},error=>{
// handle error
});
}
afterFetchingProcessData(response){
//process the data and assign to variable
this.tabledata = response;
}
或者我们应该遵循以下模式
方法2:
在组件文件中:
getApi() {
this.service.getApi().subscribe(response=> {
this.afterFetchingProcessData(response); // this might be some function in service file
},error=>{
// handle error
});
}
afterFetchingProcessData(response){
//process the data and assign to variable
this.service.tabledata = response;
}
在服务文件中只需调用 Api 并返回响应
getApi() {
return this.http
.get(url);
}
遵循方法 1 或方法 2 哪一个是最佳实践?为什么?
IMO 中,方法 2 是更好的选择。
我的看法是——
-
成分- 包括表示层,并且应该专注于向用户呈现并从他那里获取输入
-
Services- 做所有其他事情
我会更进一步将服务分为:
-
副作用服务- 负责例如API调用
-
主要服务- 封装behavior应用程序的
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)