Javascript Angular发送http请求两次
我已经在Angular 4中编写了一个应用程序。每次我尝试访问API时,angular都会发出2个请求。我的应用程序中的所有方法都会发生这种情况,包括;获取、删除、放置、发布 我将在下面添加一些代码示例。例如,我有一个NotificationComponent,它列出了数据库中的所有通知。NotificationComponent有一个方法,可以在Javascript Angular发送http请求两次,javascript,angular,typescript,Javascript,Angular,Typescript,我已经在Angular 4中编写了一个应用程序。每次我尝试访问API时,angular都会发出2个请求。我的应用程序中的所有方法都会发生这种情况,包括;获取、删除、放置、发布 我将在下面添加一些代码示例。例如,我有一个NotificationComponent,它列出了数据库中的所有通知。NotificationComponent有一个方法,可以在ngOnInit上加载通知 this.NotificationService.All(AdditionalParams) .s
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);
}
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;
});
大约相隔3秒
我有一个名为“AuthenticationService”的服务。在这个服务中,我使用ng http拦截器添加了一个http拦截器。http拦截器被添加到所有请求中。看起来是这样的
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);
}
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;
});
httpInterceptor.request().addInterceptor((数据,方法)=>{
console.log(“在httpInterceptor之前:”,数据);
var RequestOptionsIndex=null;
对于(var_i=0;_i{
res.map(response=>response.json())
.catch((错误:响应,捕获:可观察)=>{
如果(错误状态===401){
此参数为.logout();
this.router.navigate([“/login”]);
location.reload();
返回可见。抛出(“401未授权”);
}
return Observable.throw(catch);//在发布问题时,我注意到我正在订阅我的httpInterceptor.response()中的响应。addInterceptor
删除。subscribe()
修复了它。因此它变成了
httpInterceptor.response().addInterceptor((res, method) => {
return res.map(response => 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); // <-----
})//.share().subscribe()
//return res;
});
httpInterceptor.response().addInterceptor((res,method)=>{
返回res.map(response=>response)/=>response.json()
.catch((错误:响应,捕获:可观察)=>{
如果(错误状态===401){
此参数为.logout();
this.router.navigate([“/login”]);
location.reload();
返回可见。抛出(“401未授权”);
}
return Observable.throw(catch);//除非现在“401 Unauthorized”时我没有订阅发生了。有什么办法解决这个问题吗?如果您将res=res.map
添加到将res分配给结果的位置,您不会返回具有catch
的可观察对象-这有意义吗?或者我应该单独回答吗?@0mpurdy我也这么认为。我更新了我的代码,它工作了。我也更新了我的答案。如果您想订阅对于可观察对象,您应该多次返回a,有关这方面的更多详细信息可以在中找到。有几种不同的类型,例如ReplaySubject,它们也非常有用