[英]Handling Angular errors on button click
我在前端有一個角度表,其中有一個刪除按鈕,onClick 將刪除連接到 ColdFusion 后端的行。
如果在某個場景中表格頁面像往常一樣加載,但就在用戶單擊刪除按鈕之前,api 關閉
我怎樣才能拋出一個錯誤,這樣它就不會繼續到下一頁?
從delete()
函數返回錯誤代碼值。 如果一切順利,假設為0
如果出現問題,假設為1
或任何數字。
您還可以添加超時,在此之后您認為存在錯誤。
我將在此處展示一個示例,如何在連接到 http 調用的按鈕單擊時向用戶顯示錯誤,而不是執行您應該執行的操作。
成分:
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
,由於獲取數據時出錯,在這種情況下,您可以在適當的代碼塊中執行其他操作而不是刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.