我想在Angular 4中創建HTTP攔截器,但我有一些奇怪的錯誤。以下是我的錯誤:Angular 4 - HTTP攔截器
Argument of type 'Observable<Response>' is not assignable to parameter of type 'Observable<Response>'.
以下是我的代碼:
import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';
@Injectable()
export class HttpInterceptor extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.request(url, options)); // Here is the error
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.get(url, options)); // Here is the error
}
post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.post(url, body, this.getRequestOptionArgs(options))); // Here is the error
}
put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.put(url, body, this.getRequestOptionArgs(options))); // Here is the error
}
delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.delete(url, options)); // Here is the error
}
getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers(); // Here is the error
}
options.headers.append('Content-Type', 'application/json');
return options;
}
intercept(observable: Observable<Response>): Observable<Response> {
return observable.catch((err, source) => {
if (err.status == 401 && !_.endsWith(err.url, 'api/auth/login')) {
this._router.navigate(['/login']);
return Observable.empty();
} else {
return Observable.throw(err);
}
});
}
}
有誰知道是怎麼回事錯在這裏?我嘗試了3個小時的調試,但無法找到任何線索。
編輯:
我也試圖去除一切,這樣寫代碼:
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options);
}
但仍然是讓同樣的錯誤:
Argument of type 'string | Request' is not assignable to parameter of type 'string | Request'. Type 'Request' is not assignable to type 'string | Request'.
這是因爲Observable.empty()不是可觀察的。 –
Supamiu
好吧,我只是試圖刪除一切,只寫: 'request(url:string | Request,options ?: RequestOptionsArgs):Observable { return super.request(url,options); }' 但它仍然給出相同的錯誤: '類型'字符串的參數|請求「不能分配給類型爲」string |「的參數請求'。 類型'請求'不可分配給'string | Request'.' –