angular - 显示带有加载和错误情况的数据

标签 angular typescript

在 Angular 中,考虑到加载状态和错误情况,在 View 中显示数据的可靠方法是什么?

假设我们正在从后端获取文档集合,并希望使用 Angular 在我们的 View 中显示这些文档。我要考虑 3 个州。对于每个状态,我想向用户显示一条消息:

  1. 正在加载您的数据...
  2. 尝试检索您的数据时出错!
  3. 数据检索成功!

目前,我正在做以下事情。我面临的问题是“正在加载”和“错误”消息在加载阶段都会短暂显示。

我想知道其他人如何解决这个常见用例?是否可以通过为 myDocs 变量分配不同的值来实现此目的,还是必须引入另一个变量?

TS

export class MyDocsComponent implements OnInit {

    myDocs: IMyDoc | null;

    ngOnInit() {

        // get myDocs
        this.myDocsService.getMyDocs()

        // if success
        .then( myDocs => { this.myDocs = myDocs; })

        // if error: could not get myDocs from service
        .catch( error => {
            // what should go in here
            // and how should this be checked in the view
            // to display an error message to the user
            // if the data could not be retrieved
            // while also being able to display a loading message beforehand

            // currently, I am doing:
            this.myDocs = null;
            // however, this leads to the error message 
            // incorrectly being displayed 
            // while loading the data
        });
    }
}

HTML

<!-- loading -->
<div class="loading" *ngIf="!myDocs">
    Loading your data...
</div>

<!-- error -->
<div class="error" *ngIf="myDocs==null">
    Error trying to retrieve your data!                         
</div>

<!-- success -->
<div class="success" *ngIf="myDocs">
    Data retrieved successfully!
    <div class="list" *ngFor="let d of myDocs">{{ d.title }}</div>
</div>

最佳答案

尝试这样的事情

组件.ts

export class MyDocsComponent implements OnInit {

  myDocs: IMyDoc | null;

  state: 'loading' | 'loaded' | 'error' = 'loading';

  isLoading() {
    return this.state === 'loading';
  }

  isError() {
    return this.state === 'error';
  }

  isLoaded() {
    return this.state === 'loaded';
  }

  ngOnInit() {
    this.myDocsService.getMyDocs()
      .then(myDocs => {
        this.myDocs = myDocs;
        this.state = 'loaded';
      })
      .catch(error => {
        console.log(error);
        this.state = 'error';
      });
  }
}

组件.html

<div *ngIf="isLoading"  class="loading">
  Loading your data...
</div>

<div *ngIf="isError" class="error">
  Error trying to retrieve your data!
</div>

<div *ngIf="isSuccess" class="success" >
  Data retrieved successfully!
  <div class="list" *ngFor="let d of myDocs"> {{ d.title }}
  </div>
</div>

关于angular - 显示带有加载和错误情况的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49937716/

相关文章:

javascript - 弹出项目后的 Angular-cli.json

angular - 如何在 angular6 的 ng-select 中设置默认值?

javascript - 如何使用 Angular2 将 html 代码附加到 div 元素

css - 我们可以将 Mat-card 与 Anchor Tag 一起使用吗?

如果使用 formControlName, Angular Material 2 占位符会重叠值

Angular2 模板表达式在变更检测时为每个组件调用两次

Angular2 如何指向延迟加载的模块?

javascript - 将嵌套的 Json 转换为带有 parentId 的平面 Json 到每个节点

javascript - 类型缩小的 Typescript 中的 "This expression is not callable"

javascript - Typescript:通过回调设置对象成员奇怪地失败