处理由Observable引发的错误

时间:2017-05-11 13:13:58

标签: angular observable

以下HTML / JS从本地JSON文件中读取国家/地区,并将列表提供给下拉列表:



export interface Country {
  code: string;
  name: string;
}

@Injectable()
export class CountriesService {
  private url = '/assets/data/countries.json';

  constructor(private http: Http) {}

  getCountries(): Observable < Country[] > {
    return this.http.get(this.url)
      .map(res => res.json())
      .catch(err => {
        console.log(err);
        return Observable.throw(err);
      });
  }
}
&#13;
<select class="form-control custom-select" formControlName="country">
					<option value="" disabled selected hidden translate>Select Country</option>
					<option *ngFor="let country of countries$ | async" value="{{country.code}}">{{country.name}}</option>
				</select>
&#13;
&#13;
&#13;

如果在getCountries()函数中抛出错误会发生什么,我应该抓住它并显示用户友好的消息?

注意:我在组件HTML中使用async管道

1 个答案:

答案 0 :(得分:1)

您可以在订阅getCountries时在catch块中处理它。示例:添加一个名为fatalErrorMessage的新组件字段,并在catch中填充该字段,如果存在使用* ngIf =&#34; fatalErrorMessage&#34;的值,则将其显示在模板中。您的工作或展示取决于您的要求。

我猜测了你组件的逻辑。

fatalError:string = null;
ngOnInit(){
    this.countries$ = this.countryService.getCountries().catch(err => {
        console.log(err);
        this.fatalError = "Countries could not be loaded";
        return Observable.of([]); // return empty array
      });
}

模板代码:

<p *ngIf="fatalError">An unexpected error has occurred: {{fatalError}}</p>
<select class="form-control custom-select" formControlName="country">
    <option value="" disabled selected hidden translate>Select Country</option>
    <option *ngFor="let country of countries$ | async" value="{{country.code}}">{{country.name}}</option>
</select>