2017-08-10 95 views
0

我正在使用角度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()); 
    } 
} 

任何人都可以點我的權利方向我做錯了什麼?

回答

0

後進一步檢查我找到了解決我的具體問題的解決方案。

首先,我不得不更改應用到app.module.ts就這樣

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

然後http提供商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()); 
    } 
} 

我應用這些更改後,所有事情都按預期工作。

0
  1. 在這個基礎服務所有服務使用的基礎服務
  2. 繼承
  3. 寫您的全球所有的代碼在此基礎服務中

這將是最好的解決辦法