我有一个HTTP拦截器来监控401错误和超时错误。当我在其中导入服务时。它说该服务未定义
我的HTTP拦截器
// dependencies
import { Injectable } from '@angular/core';
import { ConnectionBackend, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { environment } from '../../../environments/environment';
import { Router } from '@angular/router';
import { NotificationService } from '@sharedServices/notification/notification.service';
@Injectable()
export class HttpInterceptor extends Http {
constructor(backend: XHRBackend, defaultOptions: RequestOptions, private _router: Router, private _notify: NotificationService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options)
.timeout(2000) // set timeout 15s for every request
.catch((error: Response) => {
if (error.status === 401 || error.status === 403) {
console.log('unAuthorized access');
this._router.navigate(['/login'], { queryParams: { returnUrl: this._router.url } });
}
if (error['name'] === 'TimeoutError') {
console.log(this._notify) // undefined here
}
return Observable.throw(error);
});
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.get(url, this.getRequestOptionArgs(options));
}
post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.post(url, body, this.getRequestOptionArgs(options));
}
put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.put(url, body, this.getRequestOptionArgs(options));
}
delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.delete(url, this.getRequestOptionArgs(options));
}
private updateUrl(req: string) {
return environment.origin + req;
}
private getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
const request_headers = {
'Content-Type': 'application/json',
'X-Requested-By': 'api-client'
};
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers(request_headers);
}
return options;
}
}
我的HTTP拦截工厂
// dependencies
import { XHRBackend, Http, RequestOptions } from '@angular/http';
import { HttpInterceptor } from './http-interceptor';
import { Router } from '@angular/router';
// shared services
import { NotificationService } from '@sharedServices/notification/notification.service';
export function HttpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, _router: Router, _notify: NotificationService): Http {
return new HttpInterceptor(xhrBackend, requestOptions, _router, _notify);
}
catch块内的通知未定义。我无法弄清楚为什么会这样。
我对此很陌生。我做错了什么?
答案 0 :(得分:1)
你做完了吗 -
'deps' :[NotificationService]
在模块中: -
{
'provide' : Http,
'useFactory' : HttpFactory,
'deps' : [NotificationService]
}