Я собираюсь показать пример здесь, как вы можете отобразить ошибку пользователю вместо того, чтобы делать то, что вы должны делать, по нажатию кнопки, которая связана с вызовом 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
и, поскольку при получении данных произошла ошибка, в этом случае вы можете сделать что-то еще, кроме удаления, в соответствующем блоке кода.