用角度全局处理错误

时间:2017-08-10 14:38:45

标签: angular

我正在使用angular 2,我希望拦截所有响应,并在会话过期时将用户重定向到登录页面。

我遇到This Question,我一直关注This Answer

一切都正确编译。通过在调试器中检查,我可以看到constructor已被调用,但从未到达super.request

这是我的扩展HTTP模块

import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Response, Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class AuthenticatedHttpService extends Http {

  constructor(backend:XHRBackend, defaultOptions:RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url:string | Request, options?:RequestOptionsArgs):Observable<Response> {
    return super.request(url, options).catch((error:Response) => {
      if ((error.status === 401 || error.status === 403) && (window.location.href.match(/\?/g) || []).length < 2) {
        console.log('The authentication session expires or the user is not authorised. Force refresh of the current page.');
      }
      return Observable.throw(error);
    });
  }
}

app.module.ts中,我将提供程序定义为

...
providers: [{
    provide: HttpModule,
    useClass: AuthenticatedHttpService
  }, SessionService, MyService]
...

MyService我有

import {Injectable} from "@angular/core";
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Rx";
import { environment } from '../../../environments/environment';

@Injectable()
export class MyService {
  apiUrl:string = environment.apiUrl;
  constructor(private http:Http) {
  }

  getData() {
    let headers = new Headers();
    headers.append('x-access-token', 'my-token');
    return this.http
      .get(this.apiUrl + '/getData', {headers: headers}
      ).map((res:Response) => res.json());
  }
}

有人能指出我正确的方向我做错了吗?

2 个答案:

答案 0 :(得分:0)

  1. 使用基本服务
  2. 继承此基本服务的所有服务
  3. 将所有全局代码写入此基本服务
  4. 这将是最佳解决方案

答案 1 :(得分:0)

经过进一步检查后,我找到了针对我的具体问题的解决方案。

首先,我必须对{Http Provider这样的<{p>}应用更改app.module.ts

{
  provide: AuthenticatedHttpService,
    useFactory: (backend: XHRBackend, options: RequestOptions) => {
      return new AuthenticatedHttpService(backend, options);
    },
      deps: [XHRBackend, RequestOptions]
}, 

然后在MyService我正在使用AuthenticatedHttpService代替Http

import {Injectable} from "@angular/core";
import {AuthenticatedHttpService} from '../../_services/authenticated-http.service';
import {Observable} from "rxjs/Rx";
import { environment } from '../../../environments/environment';

@Injectable()
export class MyService {
  apiUrl:string = environment.apiUrl;
  constructor(private http:AuthenticatedHttpService) {
  }

  getData() {
    let headers = new Headers();
    headers.append('x-access-token', 'my-token');
    return this.http
      .get(this.apiUrl + '/getData', {headers: headers}
      ).map((res:Response) => res.json());
  }
}

在我应用这些更改后,一切都按预期开始工作。