问:来个精通 Angular 的大哥帮忙看一段代码

2022-10-31 17:48:55 +08:00
 anonymous2351d00
 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 状态的代码,感觉弄得我代码很不干净,有没有什么方法能尽量让改变页面状态代码精简些,让我的代码干净些

1968 次点击
所在节点    Angular
9 条回复
anonymous2351d00
2022-10-31 17:49:56 +08:00
十分困扰(艹皿艹 ),i can't write some cleancode
Aloento
2022-10-31 17:55:20 +08:00
前端要那么干净干什么((( hhhhhhhhhhhhhhhhhhh
yuyanggongzi
2022-10-31 17:57:59 +08:00
用管道
this.http.get().pipe(tap(() => this.loading=false)).subscribe()
charlie21
2022-10-31 18:41:42 +08:00
服务和组件状态解耦,是很对的

组件状态都是本地状态而已,在回调里更新。具体可以是 pipe tap 里或 subscribe 里。

however, 如果想要更 neat, 在不借助第三方库的情况下,可考虑让服务直接返回一个 loading$ observable , 视图里直接用 async pipe 打印之。逻辑挪到了服务里,组件直接消费服务

<spin [spining]="isLoading$ | async"></spin>

参考 https://www.thinktecture.com/en/angular/understanding-the-async-pipe/
anonymous2351d00
2022-11-01 11:35:26 +08:00
@yuyanggongzi 假设 this.http 抛出异常了,tap 可不可以正确接收一个 error 呢,还是我还得 去 catchError 改变状态


@charlie21 大佬平常使用哪种方法?显式调用然后改变状态还是 async 去调用返回 ob(true)/ob(false) ?
anonymous2351d00
2022-11-01 11:35:37 +08:00
@Aloento 看着难受,红红火火恍恍惚惚
lovepocky
2022-11-01 12:15:15 +08:00
你难受的地方是页面逻辑耦合到服务调用里面了吧?
那可以把服务调用的状态暴露出来一个 observable (比如 ishttpfetching$),然后页面去订阅它
yuyanggongzi
2022-11-01 13:59:49 +08:00
@anonymous2351d00 异常我是在拦截器里面统一处理的,最后返回一个自定义的正常流
beginor
2022-11-01 15:07:03 +08:00
可以封装成 promise , 然后用 async await + try catch finally 解决

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/891532

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX