我正在使用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());
}
}
有人能指出我正确的方向我做错了吗?
答案 0 :(得分:0)
这将是最佳解决方案
答案 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());
}
}
在我应用这些更改后,一切都按预期开始工作。