【问题标题】:Errors handling in resolve class angular2解析类 angular2 中的错误处理
【发布时间】:2017-06-10 02:41:49
【问题描述】:

我正在基于 Angular2 Docs 在 Angular 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();

  }
}

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

【问题讨论】:

    标签: angular routes resolve


    【解决方案1】:

    你可以发现错误

      resolve(route: ActivatedRouteSnapshot,  state: RouterStateSnapshot):Observable<Category[]> {
    
         return this.categoryService.GetAll().catch(err => console.log(err));
    
      }
    

    【讨论】:

      【解决方案2】:

      在 resolve 方法中我需要返回一个 observable

      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); // <-----
              }
            ));
      }
      

      【讨论】:

      • )); 应该是);
      猜你喜欢
      • 2016-08-10
      • 2011-03-11
      • 2012-12-13
      • 2016-08-06
      • 2012-06-11
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      相关资源
      最近更新 更多