 
- Angular 2 教程
- Angular 2 - 主页
- Angular 2 - 概述
- Angular 2 - 环境
- Angular 2 - 你好世界
- Angular 2 - 模块
- Angular 2 - 架构
- Angular 2 - 组件
- Angular 2 - 模板
- Angular 2 - 指令
- Angular 2 - 元数据
- Angular 2 - 数据绑定
- 使用 HTTP 进行 CRUD 操作
- Angular 2 - 错误处理
- Angular 2 - 路由
- Angular 2 - 导航
- Angular 2 - 表单
- Angular 2 - CLI
- Angular 2 - 依赖注入
- Angular 2 - 高级配置
- Angular 2 - 第三方控件
- Angular 2 - 数据显示
- Angular 2 - 处理事件
- Angular 2 - 转换数据
- Angular 2 - 自定义管道
- Angular 2 - 用户输入
- Angular 2 - 生命周期挂钩
- Angular 2 - 嵌套容器
- Angular 2 - 服务
- Angular 2 有用资源
- Angular 2 - 问题与解答
- Angular 2 - 快速指南
- Angular 2 - 有用的资源
- Angular 2 - 讨论
Angular 2 - 错误处理
Angular 2 应用程序可以选择错误处理。这是通过包含 ReactJS catch 库然后使用 catch 函数来完成的。
让我们看看错误处理所需的代码。可以将此代码添加到使用 http 进行 CRUD 操作的章节的顶部。
在product.service.ts 文件中,输入以下代码 -
import { Injectable } from '@angular/core'; 
import { Http , Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/do'; 
import 'rxjs/add/operator/catch'; 
import { IProduct } from './product';  
@Injectable() 
export class ProductService { 
   private _producturl = 'app/products.json'; 
   constructor(private _http: Http){}  
   getproducts(): Observable<IProduct[]> { 
      return this._http.get(this._producturl) 
      .map((response: Response) => <IProduct[]> response.json()) 
      .do(data => console.log(JSON.stringify(data))) 
      .catch(this.handleError); 
   }  
   
   private handleError(error: Response) { 
      console.error(error); 
      return Observable.throw(error.json().error()); 
   } 
}
- catch 函数包含到错误处理函数的链接。 
- 在错误处理函数中,我们将错误发送到控制台。我们还将错误抛出回主程序,以便继续执行。 
现在,每当您收到错误时,它都会被重定向到浏览器的错误控制台。