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

查看:82
本文介绍了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.

因此我不明白.为什么不像在实例中创建数据那样创建数据呢?该实例只需要加载一次数据即可查询,而不必提出新的请求.更不用说返回实际数据,而不是承诺/可观察到的数据.如果有人可以解释这一点并告诉我我想念的东西,我会喜欢的.预先感谢.

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层与Model层之间的耦合,从而使设计更简洁,更易于开发,测试和维护.

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天全站免登陆