Skip to content

Commit adac7c3

Browse files
author
ying.liu
committed
add angular async and spin
1 parent 3908c66 commit adac7c3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

frontend/angular-best-practices.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,54 @@ createForm() {
6868
- Use `providedIn: 'root'` for all services, either global or local, which should be available as singletons.
6969
- Use file structure to scope services. A module can only use services that are in its subfoler or share the same parent folder.
7070
- Use `providers: []` for services that 1) need initialization (such as `myService.forRoot()`) or 2) inside `@Component` or `@Directive` for scoped mulitple-instance services.
71+
72+
## 异步操作和 Spin
73+
74+
RxJS 有二种常见的数据处理方式,用`subscribe()``pipe()`.
75+
76+
```ts
77+
// 方式一: recommended
78+
this.service.getData().subscribe(data => this.onSuccess(data), error => this.handleError(error))
79+
80+
// 方式二
81+
this.service
82+
.getAll()
83+
.pipe(
84+
map(data => this.onSuccess(data)),
85+
catchError(error => of(this.handleError(error))),
86+
)
87+
.subscribe()
88+
```
89+
90+
建议采用方式一的原因在最后一步分别处理正常和错误数据而不用顾虑处理结果, 避免了方式二为了保证统一输出所需要的`of()`转换。
91+
92+
建议`pipe()`只用于调试,log 或需要数据转换但不能用`subscribe()`的场合。
93+
94+
当运行后台任务时需要显示 Spinner 或 loading 信息。建议采用如下模式:
95+
96+
```ts
97+
// recommended
98+
this.startSpin()
99+
this.service
100+
.getData()
101+
.subscribe(data => this.onSuccess(data), error => this.handleError(error))
102+
.add(() => this.stopSpin())
103+
```
104+
105+
采用`finalize()`来在正常或错误情况下都停止显示 spinner 或 loacing 信息。此处的`finalize()``error``complete`之后调用。其效果和如下二种方法一致:
106+
107+
```ts
108+
//
109+
this.startSpin()
110+
const subscription = this.service
111+
.getData()
112+
.subscribe(data => this.onSuccess(data), error => this.handleError(error))
113+
subscription.add(() => this.stopSpin())
114+
115+
// 或者
116+
this.startSpin()
117+
this.service
118+
.getData()
119+
.pipe(finalize(() => this.stopLoading())
120+
.subscribe(data => this.onSuccess(data), error => this.handleError(error))
121+
```

0 commit comments

Comments
 (0)