简体   繁体   English

处理按钮单击时的角度错误

[英]Handling Angular errors on button click

I have an angular table in the front end with a delete button in it that onClick will delete the row, connected to ColdFusion backend.我在前端有一个角度表,其中有一个删除按钮,onClick 将删除连接到 ColdFusion 后端的行。

If in a scenario the table page loads as usual, but right before the user clicks the delete button, the api goes down如果在某个场景中表格页面像往常一样加载,但就在用户单击删除按钮之前,api 关闭

How can I throw an error so it doesn't continue then on to the next page?我怎样才能抛出一个错误,这样它就不会继续到下一页?

Return an error code value from your delete() function.delete()函数返回错误代码值。 Let's say 0 if everything went ok and 1 or any number if something went wrong.如果一切顺利,假设为0如果出现问题,假设为1或任何数字

You can also add a timeout after which you consider that there is an error.您还可以添加超时,在此之后您认为存在错误。

I'm going show an example here how you can display an error to the user instead of doing what you are supposed to do, on a button click, which is connected to http call.我将在此处展示一个示例,如何在连接到 http 调用的按钮单击时向用户显示错误,而不是执行您应该执行的操作。

Stackblitz Demo Stackblitz 演示

component:成分:

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
          }         
        );
  }
}

template:模板:

<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>

just click on the button click me and since there is an error getting the data, you can do something else in this case rather the deleting, in the appropriate block of code.只需单击按钮click me ,由于获取数据时出错,在这种情况下,您可以在适当的代码块中执行其他操作而不是删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM