すべての http 応答を 1 か所から確認したい。たとえば、認証ステータス。応答で、ユーザーが認証されなくなったことが示されている場合は、リダイレクトするか、何か他のことを行います。それを行う方法はありますか。
質問する
3152 次
2 に答える
6
どうぞ
そのようなサービスを作成します
export const JWT_RESPONSE_HEADER = 'X-Auth-Token';
@Injectable()
export class AuthHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
const request = super.request(url, this.appendAuthHeader(options));
request.map(this.saveToken);
return request;
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
const request = super.get(url, this.appendAuthHeader(options));
request.map(this.saveToken);
return request;
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
const request = super.post(url, body, this.appendAuthHeader(options));
request.map(this.saveToken);
return request;
}
put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
const request = super.put(url, body, this.appendAuthHeader(options));
request.subscribe(this.saveToken);
return request;
}
delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
const request = super.delete(url, this.appendAuthHeader(options));
request.map(this.saveToken);
return request;
}
private appendAuthHeader(options?: RequestOptionsArgs): RequestOptionsArgs {
let mergedOptions: RequestOptionsArgs;
if (!options) {
mergedOptions = { headers: new Headers() };
} else {
mergedOptions = options;
}
const token = localStorage.getItem(JWT_RESPONSE_HEADER);
const isTokenSet = mergedOptions.headers.has('Authorization');
if (token && !isTokenSet) mergedOptions.headers.append('Authorization', `Bearer ${token}`);
return mergedOptions;
}
private saveToken(res: Response): void {
const token = res.headers.get(JWT_RESPONSE_HEADER);
if (token) localStorage.setItem(JWT_RESPONSE_HEADER, token);
}
}
そして、このように app.module.ts に含めます
@NgModule({
imports: [
BrowserModule,
ContentModule,
routing,
HttpModule
],
declarations: [
AppComponent,
LoginComponent
],
providers: [
appRoutingProviders,
LoginService,
{
provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new AuthHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
httpを使用する他のサービスに変更を加える必要はありません
于 2016-09-30T12:12:59.317 に答える