我已經在Angular 4中編寫了一個應用程序。它每次嘗試訪問一個API時看起來像角度發出2個請求。這發生在我的應用程序中的所有方法,包括; GET,DELETE,PUT,POSTAngular發送一個http請求兩次
我會在下面添加一些代碼示例。例如,我有一個NotificationComponent,它列出了數據庫中的所有通知。 NotificationComponent有一個方法可以在ngOnInit
上加載通知;
this.NotificationService.All(AdditionalParams)
.subscribe(
notifications => {
this.AllNotifications.Notifications = notifications.data;
this.AllNotifications.Data = notifications;
this.AllNotifications.Loading = false;
this.AllNotifications.Loaded = true;
this.AllNotifications.HasRequestError = false;
},
(error)=> {
this.AllNotifications.Loading = false;
this.AllNotifications.Loaded = false;
this.AllNotifications.RequestStatus = error.status;
if (typeof error.json == 'function' && error.status!=0) {
let errorObject = error.json();
this.AllNotifications.RequestError = errorObject;
} else {
this.AllNotifications.RequestError = "net::ERR_CONNECTION_REFUSED";
}
this.AllNotifications.HasRequestError = true;
});
}
該方法訂閱了NotificationService中的All方法。 All方法看起來像這樣;
All(AdditionalParams: object): Observable<any> {
let options = new RequestOptions({ headers: this.headers });
let params = new URLSearchParams();
//params.set("token", this.authenticationService.token);
for (var key in AdditionalParams) {
params.set(key, AdditionalParams[key]);
}
options.params = params;
return this.http.get(this.notificationsUrl, options)
.map(response => response.json())
.catch(this.handleError);
}
不知何故請求被髮送兩次。我認爲這在我的控制檯日誌中;
XHR finished loading: GET "[REMOVED]/notifications?page=1&event=1&token=eyJ0eXAiOi…GkiOiJ1bGYxSnJPa1Zya0M2NmxDIn0.3kA8Pd-tmOo4jUinJqcDeUy7mDPdgWpZkqd3tbs2c8A"
XHR finished loading: GET "[REMOVED]/notifications?page=1&event=1&token=eyJ0eXAiOi…GkiOiJ1bGYxSnJPa1Zya0M2NmxDIn0.3kA8Pd-tmOo4jUinJqcDeUy7mDPdgWpZkqd3tbs2c8A"
相隔約3秒。
我有一個名爲「AuthenticationService」的服務。在這個服務中,我添加了一個使用ng-http-interceptor的http攔截器。 http攔截器被添加到所有請求中。它看起來像這樣;
httpInterceptor.request().addInterceptor((data, method) => {
console.log ("Before httpInterceptor: ", data);
var RequestOptionsIndex = null;
for (var _i = 0; _i < data.length; _i++) {
if (typeof data[_i] == 'object' && data[_i].hasOwnProperty('headers')){
RequestOptionsIndex = _i;
}
}
if (RequestOptionsIndex == null) {
let options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
let params = new URLSearchParams();
data.push(options);
RequestOptionsIndex = data.length-1;
}
//console.log (data, this.loginURL, 'RequestOptionsIndex: ', RequestOptionsIndex);
if (!data[RequestOptionsIndex].hasOwnProperty('headers')){
data[RequestOptionsIndex].headers = new Headers({'Content-Type': 'application/json'});
}
if (data[0]!=this.loginURL && (data[RequestOptionsIndex].headers.get('Authorization')=="" || data[RequestOptionsIndex].headers.get('Authorization')==null)) {
data[RequestOptionsIndex].headers.append("Authorization", 'Bearer ' + this.token);
}
if (data[RequestOptionsIndex].params!=undefined && data[RequestOptionsIndex].params!=null) {
data[RequestOptionsIndex].params.set('token', this.token);
}else {
let params = new URLSearchParams();
params.set('token', this.token);
data[RequestOptionsIndex].params = params;
}
console.log ("httpInterceptor data", data, ": RequestOptionsIndex", RequestOptionsIndex);
return data;
});
httpInterceptor.response().addInterceptor((res, method) => {
res.map(response => response.json())
.catch((err: Response, caught: Observable<any>) => {
if (err.status === 401) {
this.logout();
this.router.navigate(["/login"]);
location.reload();
return Observable.throw("401 Unauthorized");
}
return Observable.throw(caught); // <-----
}).subscribe()
return res;
});
除了現在我沒有訂閱時,「401未經授權」發生。有辦法解決這個問題嗎? – LogicDev
如果你添加了res = res.map',那麼你將不會返回帶有catch的觀測值,這裏你將res分配給結果 - 這是否有意義,還是應該單獨回答? – 0mpurdy
@ 0mpurdy我也這麼認爲。我更新了我的代碼,它工作。我也更新了我的答案。 – LogicDev