我在this guide之后有一个扩展的Http服务,它本质上是一个请求错误处理程序。当请求中的错误返回401状态时,我将其重定向到“拒绝”页面。目前,我能够捕获错误并重定向它们没有问题,我还可以看到状态响应输出到控制台。但是,我希望能够通过我的组件订阅/显示从服务调用返回的错误的正文。
我希望有人可以告诉我如何使用此服务并在我拒绝的组件中显示错误。
这是我的扩展类的样子:
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Request, Http, XHRBackend, RequestOptions, RequestOptionsArgs, Response} from '@angular/http';
import {Observable} from 'rxjs';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable
export class ErrorHttpService extends Http {
constructor(backend: XHRBackend, defaultOptions: RequestOptions, private router:Router){
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options)
.catch((error: Response) => {
if ((error.status === 401)) {
this.router.navigate(['denied'])
}
return Observable.throw(error); //how can I get this into 'denied'
});
}
}
这是我的denied.component.ts:
import {Component, OnInit} from "@angular/core";
import {ErrorHttpService} from "../_services/error-http.service";
//component info removed
export class DeniedComponent implements OnInit {
constructor(private service: ErrorHttpService){}
ngOnInit(){
//how to subscribe to error thrown in ErrorHttpService
}
}