<style>
.reveal, .reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 {
font-family: "Source Sans Pro", "Helvetica Neue", Helvetica, Arial, "Microsoft JhengHei", Meiryo, "MS ゴシック", "MS Gothic", sans-serif;
}
h1, h2, h3, h4, h5, h6 {
text-transform: none !important;
}
.color-yellow{
color: yellow;
}
</style>
# AngularJS
*****
Factory & refactor
Jacky.H.Hung
---
[11:07 PM] 嗯所以我有點混亂為什麼
```
var STORE
var factory ={
get: get,
set: set
}
return factory;
function get(){ //.. }
function set(){ //.. }
```
---
### 先說:此範例`命名`不好造成誤解 sorry
---
### AngularJS Services 有哪些?
- factory
- service
- provider
> factory, service 或 provider,其本質上都相同,背後的實作都是 provider
---
## 假設我要寫一隻關於操作 `userInfo` 的 services
---
## 如果用 service 寫:
```
function userInfo(){
this.getUser = function(){ //do.. };
this.setName = function(){ //do.. };
this.setPhone = function(){ //do.. };
this.setEmail = function(){ //do.. };
};
```
---
## 如果用 Factory 寫:
```
function userInfo(){
return{
getUser: function(){ //do.. },
setName: function(){ //do.. },
setPhone: function(){ //do.. },
setEmail: function(){ //do.. },
}
};
```
Factory 是閉包的概念,因此必須要有一個 return
建議都使用 Factory 建立 services
參考: [AngularJS 1.5 最佳實務 - 格物致知](https://amobiz.github.io/2016/04/15/angularjs-1.5-best-practices/#就使用-factory-函數-忘記-service-和-provider-吧)
---
## Code Style refactor
*****
根據: [Angular 1 Style Guide](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#manual-annotating-for-dependency-injection)
把 Factory 修該為 →
---
```
function userInfo(){
var userApi = {
getUser: getUser,
setName: setName,
setPhone: setPhone,
setEmail: setEmail,
}
return userApi;
function getUser(){ //do.. }
function setName(){ //do.. }
function setPhone(){ //do.. }
function setEmail(){ //do.. }
function check
};
```
---
## 重構後有什麼好處?
- 當 factory 變大的時候 return 的對象會形同 api 列表,一眼就看出有什麼可以操作<!-- .element: class="fragment" data-fragment-index="1" -->
- return 之上是內部封閉資料區域<!-- .element: class="fragment" data-fragment-index="2" -->
- return 之下是所有內部 function<!-- .element: class="fragment" data-fragment-index="3" -->
- return 對象可自定義被呼叫的公開項目<!-- .element: class="fragment" data-fragment-index="4" -->
- function 間的呼叫變的簡單<!-- .element: class="fragment" data-fragment-index="5" -->
---
# END
{"metaMigratedAt":"2023-06-14T11:34:40.263Z","metaMigratedFrom":"Content","title":"AngularJS","breaks":true,"contributors":"[]"}