Angular 2 服务......毫无意义? [英] Angular 2 Service... Pointless?

查看:25
本文介绍了Angular 2 服务......毫无意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 angular 2 大约 2 周了,我喜欢它,除了一件事......服务.尽管使用它们,但为了顺应社会,我不明白这一点,希望有人能解释一下原因.

I have been using angular 2 for about 2 weeks now and I love it with the exception of one thing... Services. Despite using them, to conform to society, I don't understand the point and I hope some one can explain the reasoning.

服务除了加载数据之外不做任何事情.更不用说 9/10 我注入它的任何组件都必须具有类似的功能来处理返回的数据并使其可用.我对它们的另一个大问题是开销.让我们说(按照英雄教程)我运行一个ajax请求(使用服务)来创建一个英雄列表,我点击一个,现在我加载一个新页面,在那里我收到id并使用相同的服务运行另一个请求.

Services don't do anything besides load data. Not to mention 9/10 what ever component I inject it into has to have similar functions to handle the data returned and make it usable. Another big problem I have with them is the overhead. Lets say (Following the heroes tutorial) I run an ajax request (using the service) to create a list of heroes, I click on one and now I load a new page where I receive the id and run yet another request using the same service.

所以我不明白.为什么不创建它更像是一个实例,其中数据只需要加载一次并且可以被查询而不是发出全新的请求.更不用说返回实际数据而不是 promises/observable.如果有人可以解释这一点并告诉我我错过了什么,我会喜欢的.提前致谢.

Thus I don't understand. Why not create it more like an instance where the data only needs to be loaded once and can be queried instead of making whole new requests. Not to mention returning actual data instead of promises/observable. If some one can explain this and tell me what I am missing I would love that. Thanks in advance.

推荐答案

服务封装了业务关注点,并将它们与 UI 关注点或控制器关注点分开,后者同时管理它们.

Services encapsulates business concerns and separates them from UI concerns or the controller concerns, which governs them both.

服务注重功能.UI 专注于呈现.控制器专注于管理 UI 和服务交互.

Services focus on functionality. UI focuses on presentation. Controllers focus on managing UI and Service interactions.

好处是可维护性.UI 逻辑与业务逻辑的分离旨在减少 UI 层和模型层之间的耦合,从而使设计更简洁,更易于开发、测试和维护.

The benefit is maintainability. The separation of UI logic from business logic is intended to reduce the coupling between the UI layer and the Model layer, leading to a cleaner design that is easier to develop, test, and maintain.

在 Angular2 中:

In Angular2:

class --> Controller
injectable services --> Model
component view template --> View

这篇关于Angular 2 服务......毫无意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆