【问题标题】:Unable to show error message on table with the Invalid search data (no data from API, gives 404)无法在包含无效搜索数据的表上显示错误消息(没有来自 API 的数据,给出 404)
【发布时间】:2021-04-02 18:43:52
【问题描述】:

能够在 API 给出响应时填充数据,如果 API 无法给出响应,请帮助我如何在表格中显示“未找到结果”之类的错误消息。我在下面尝试过,请参考正在工作的 stackblitz。

const dataUrl =
          "https://raw.githubusercontent.com/l-lin/angular-datatables/master/demo/src/data/data3.json"; //invalid API

const dataUrl =
          "https://raw.githubusercontent.com/l-lin/angular-datatables/master/demo/src/data/data.json"; // ---- valid API
    
        this.http.get(dataUrl).subscribe(response => {
          this.persons = response.data.map(x => ({
            ...x,
            check: false,
            test: x.firstName
          }));
          this.dtTrigger.next();
        });
      }

Stackblitz

【问题讨论】:

  • 看看我的回答。如果对您有用,请将答案标记为已接受。

标签: angular angular-datatables


【解决方案1】:

订阅函数的第二个参数是错误回调。

您可以执行以下操作:

this.http.get(dataUrl).subscribe(response => {
          this.persons = response.data.map(x => ({
            ...x,
            check: false,
            test: x.firstName
          }));
          this.dtTrigger.next();
        }, errResponse => {
          // Your error display logic here.
        });

【讨论】:

    【解决方案2】:

    首先,添加两个变量:

    noDataErrorMessage = "No results found";
    isCalledAPI = false;
    

    更改 HTTP API 调用为:

    this.http.get(dataUrl).subscribe(
          response => {
            this.persons = response.data.map(x => ({
              ...x,
              check: false,
              test: x.firstName
            }));
            this.dtTrigger.next();
          },
          () => {
            if (!this.isCalledAPI) this.isCalledAPI = true;
          }
        );
    

    如果您调用 API,它将设置状态。

    最后,在表格后添加HTML:

    <p *ngIf="isCalledAPI && !persons.length" style="text-align:center">{{ noDataErrorMessage }}</p>
    

    当您使用错误的 URL 或没有数据的有效 URL 时,将显示此消息。

    工作演示StackBlitz

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 2021-03-02
      • 1970-01-01
      • 2019-11-23
      • 2021-06-23
      相关资源
      最近更新 更多