如何使数据请求完成并加载动画消失

时间:2018-11-28 08:17:28

标签: angular typescript

enter code here`
     ngOnInit() {
        this.loading = true;
        this.jobExecution$ = this.route.params
          .pipe(mergeMap(
            val => this.jobsService.getJobExecution(val.id)
          ),
          catchError((error) => {
            console.log(error);
            if (HttpAppError.is404(error) || HttpAppError.is400(error)) {
              this.loading = false;
              this.cancel();
            }
            this.loggerService.log('error while loading Job Execution Details', error);
            this.loading = false;
            this.notificationService.error('错误', 'error');
            return EMPTY;
          }));
      }`

如何使数据请求完成并加载动画消失? 取消动画并消失的代码不知道将动画添加到何处。

3 个答案:

答案 0 :(得分:2)

您可以使用点击https://www.learnrxjs.io/operators/utility/do.html

ngOnInit() {
        this.loading = true;
        this.jobExecution$ = this.route.params
          .pipe(mergeMap(
            val => this.jobsService.getJobExecution(val.id)
          ),
          tap(
            (next) => (this.loading = false),
            (error) => {
              console.log(error);
            if (HttpAppError.is404(error) || HttpAppError.is400(error)) {
              this.cancel();
            }
            this.loggerService.log('error while loading Job Execution Details', error);
            this.loading = false;
            this.notificationService.error('错误', 'error');
            return EMPTY;
            },
          ));
}

答案 1 :(得分:2)

  ngOnInit() {
    this.loading = false;  //*always disable loader on ngOnInit
    this.getData();
  }

  getData(){
    this.loading = true;  //correct
    this.jobExecution$ = this.route.params
    .pipe(mergeMap(
      val => this.jobsService.getJobExecution(val.id)
    ).then( //on success
      this.loading = false; //***disable loader in here too
    ),
    catchError((error) => {
      console.log(error);
      if (HttpAppError.is404(error) || HttpAppError.is400(error)) {
        this.loading = false; //correct
        this.cancel();
      }
      this.loggerService.log('error while loading Job Execution Details', error);
      this.loading = false; //correct
      this.notificationService.error('错误', 'error');
      return EMPTY;
    }));
  }

尝试这种方式。遵循最佳做法。 还要在成功响应时禁用加载程序。

答案 2 :(得分:0)

我个人希望使用 finalize ,因为它在可观察到的完成(成功或错误)时运行 参见:https://www.learnrxjs.io/operators/utility/finalize.html

ngOnInit() {
    this.loading = true;

    this.jobExecution$ = this.route.params
      .pipe(
        mergeMap(val => this.jobsService.getJobExecution(val.id)),
        catchError((error) => {
          if (HttpAppError.is404(error) || HttpAppError.is400(error)) {
            this.cancel();
          }

          this.loggerService.log('error while loading Job Execution Details', error);
          this.notificationService.error('错误', 'error');
          return EMPTY;
        }),
        finalize(() => this.loading = false)
      )
   );
}