解析类angular2中的错误处理

时间:2017-01-25 03:13:23

标签: angular routes resolve

我正在基于Angular2 Docs在角度2中创建一个解析类,这是我的类

//Angular core
import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/catch'
//Service
import { CategoryService } from '../services/category.services';

//Model
import { Category } from '../model/category.interface';

@Injectable()
export class ListCategoryResolve implements Resolve<Category[]> {

  constructor(private categoryService: CategoryService, private router: Router) { }

  resolve(route: ActivatedRouteSnapshot,  state: RouterStateSnapshot):Observable<Category[]> {

     return this.categoryService.GetAll();

  }
}

此时如何处理错误?,例如我的服务已关闭

2 个答案:

答案 0 :(得分:0)

您可以捕获错误

  resolve(route: ActivatedRouteSnapshot,  state: RouterStateSnapshot):Observable<Category[]> {

     return this.categoryService.GetAll().catch(err => console.log(err));

  }

答案 1 :(得分:0)

在解决方法中,我需要返回一个可观察的

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Category[]> {
    return this.categoryService.GetAll()     
      .catch(
      (err: Response, caught: Observable<Category[]>) => {
          if (err !== undefined) {
            this.router.navigate(["/error",{  outlet: 'error'}]);
            return Observable.throw('The Web server (running the Web site) is currently unable to handle the HTTP request due to a temporary overloading or maintenance of the server.');
          }
          return Observable.throw(caught); // <-----
        }
      ));
}