Angular 1.x : 具体场景什么时候使用控制器/服务
Angular 1.x : Specific Scenario When To Use Controller / Service
假设,在网络应用程序中,特定的 JSON 经常在多个页面中使用,例如:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
因此,为所有员工获得 firstName()
或 lastName()
应该被视为控制者或服务的一部分?
我只能考虑使用 services,因为它经常在应用程序和控制器中使用,以获取此数据,而且它也会更薄。
这是正确的方法吗?
您有以下选项:
- Make a REST/HTTP call every time you need this data in a certain controller. Therefore, create a EmployeesService which calls the HTTP
endpoint to get the data.
- Call the data once, and store it in a service. Afterwards, inject the service everywhere you need the data.
- Fetch the data from the HTTP endpoint when your app starts, and store it in the local storage of the browser or inside the $rootScope,
so you can access it from everywhere.
最终取决于:
- 您的 app/how 数据量有多大?
- 多久更新一次此数据?
- 哪些视图需要访问此数据?
所以是的,有了服务,您就安全了。然后,将其注入控制器并从那里使用它。数据进入服务的方式和频率:您的决定。
假设,在网络应用程序中,特定的 JSON 经常在多个页面中使用,例如:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
因此,为所有员工获得 firstName()
或 lastName()
应该被视为控制者或服务的一部分?
我只能考虑使用 services,因为它经常在应用程序和控制器中使用,以获取此数据,而且它也会更薄。
这是正确的方法吗?
您有以下选项:
- Make a REST/HTTP call every time you need this data in a certain controller. Therefore, create a EmployeesService which calls the HTTP endpoint to get the data.
- Call the data once, and store it in a service. Afterwards, inject the service everywhere you need the data.
- Fetch the data from the HTTP endpoint when your app starts, and store it in the local storage of the browser or inside the $rootScope, so you can access it from everywhere.
最终取决于:
- 您的 app/how 数据量有多大?
- 多久更新一次此数据?
- 哪些视图需要访问此数据?
所以是的,有了服务,您就安全了。然后,将其注入控制器并从那里使用它。数据进入服务的方式和频率:您的决定。