codeRun(code: string): void { if (!this.viewState.source || !this.viewState.source.id) return; this.toolbarState.loading.run = true; this.toolbarState.enable.stop = true; this.viewTableState.loading = true; const param: ViewTestExecute = { sourceId: this.viewState.source.id, scriptType: 'SQL', size: this.toolbarState.limit.value, script: code, variables: [], columns: [], countTotal: true }; this.dataProviderService .execute(param) .pipe( catchError(exception => { this.toolbarState.loading.run = false; this.toolbarState.enable.stop = false; this.viewTableState.loading = false; throw exception; }) ) .pipe(takeUntil(this.destroy$)) .subscribe((result: QueryResult) => { this.viewState.execute = param this.toolbarState.loading.run = false; this.toolbarState.enable = {run: true, stop: false, save: true, setting: false, copy: false}; this.viewTableState = {...result, loading: false}; }); }
如上面这段代码,因为页面的标签例如 <spin [spining]='xxxloading'></spin>
这样,有一个加载状态,但是用
this.loading = true this.http.get().subscribe(xx=>this.loading=false)
这种改变 loading 状态的代码,感觉弄得我代码很不干净,有没有什么方法能尽量让改变页面状态代码精简些,让我的代码干净些
1 anonymous2351d00 OP 十分困扰(艹皿艹 ),i can't write some cleancode |
![]() | 2 Aloento 2022-10-31 17:55:20 +08:00 ![]() 前端要那么干净干什么((( hhhhhhhhhhhhhhhhhhh |
![]() | 3 yuyanggongzi 2022-10-31 17:57:59 +08:00 ![]() 用管道 this.http.get().pipe(tap(() => this.loading=false)).subscribe() |
4 charlie21 2022-10-31 18:41:42 +08:00 via iPhone ![]() 服务和组件状态解耦,是很对的 组件状态都是本地状态而已,在回调里更新。具体可以是 pipe tap 里或 subscribe 里。 however, 如果想要更 neat, 在不借助第三方库的情况下,可考虑让服务直接返回一个 loading$ observable , 视图里直接用 async pipe 打印之。逻辑挪到了服务里,组件直接消费服务 <spin [spining]="isLoading$ | async"></spin> 参考 https://www.thinktecture.com/en/angular/understanding-the-async-pipe/ |
5 anonymous2351d00 OP @yuyanggongzi 假设 this.http 抛出异常了,tap 可不可以正确接收一个 error呢,还是我还得 去 catchError 改变状态 @charlie21 大佬平常使用哪种方法?显式调用然后改变状态还是 async 去调用返回 ob(true)/ob(false) ? |
6 anonymous2351d00 OP @Aloento 看着难受,红红火火恍恍惚惚 |
7 lovepocky 2022-11-01 12:15:15 +08:00 via iPhone 你难受的地方是页面逻辑耦合到服务调用里面了吧? 那可以把服务调用的状态暴露出来一个 observable (比如 ishttpfetching$),然后页面去订阅它 |
![]() | 8 yuyanggongzi 2022-11-01 13:59:49 +08:00 @anonymous2351d00 异常我是在拦截器里面统一处理的,最后返回一个自定义的正常流 |
![]() | 9 beginor 2022-11-01 15:07:03 +08:00 via Android 可以封装成 promise , 然后用 async await + try catch finally 解决 |