【问题标题】:Handling Angular errors on button click处理按钮单击时的角度错误
【发布时间】:2019-03-27 02:16:06
【问题描述】:

我在前端有一个角表,其中有一个删除按钮,onClick 将删除该行,连接到 ColdFusion 后端。

如果在某种情况下,表格页面照常加载,但在用户单击删除按钮之前,api 会关闭

我怎样才能抛出一个错误,让它不会继续到下一页?

【问题讨论】:

  • 我们需要更多细节。这个表是否使用了 observable、http 调用等

标签: angular error-handling onclick


【解决方案1】:

从您的 delete() 函数返回错误代码值。如果一切正常,我们说0,如果出现问题,我们说1 或任何数字

您也可以添加timeout,之后您认为有错误。

【讨论】:

    【解决方案2】:

    我将在此处展示一个示例,如何在连接到 http 调用的按钮单击时向用户显示错误,而不是执行您应该执行的操作。

    Stackblitz Demo

    组件:

    import { Component } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular 5';
    
      logs: string[] = [];
    
      errorFetch: boolean = false;
    
      constructor(private http: HttpClient) { }
    
      onClick(event) {
        this.http.get("https://weather.cit.api.here.com/weather/1.0/report.json?product=forecast_7days_simple&latitude=" + "&longitude=" + "&app_id=" + "&app_code=" + "jsonpCallback")
            .subscribe(result => {
                // if everything goes well do what you want here
                console.log("success getting weather results");
              },
              (err) => {
                //if the back end is down
                //error getting data
                //set a flag to show an error
                this.errorFetch = true;
    
                //here click on the button click me, to see the result
                //because the weather api is not responding you get to this block
                //of code
              },
              () => {
                //subscribe has finished
              }         
            );
      }
    }
    

    模板:

    <hello name="{{ name }}"></hello>
    <p>
      Start editing to see some magic happen :)
    </p>
    
    <button (click)="onClick($event)">click me</button>
    
    <div *ngIf="errorFetch" style="color:red;"> error getting weather data</div>
    

    只需单击按钮click me,由于获取数据时出错,在这种情况下,您可以在适当的代码块中执行其他操作,而不是删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2013-03-05
      • 2018-08-22
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多