Angular发送两次http请求

时间:2017-08-06 17:05:42

标签: javascript angular typescript

我已经在Angular 4中编写了一个应用程序。看起来每次尝试访问API时,angular会发出2个请求。这适用于我的应用程序中的所有方法,包括;获取,删除,投入,发布

我将在下面添加一些代码示例。例如,我有一个NotificationComponent,它列出了来自数据库的ll通知。 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;
        });

1 个答案:

答案 0 :(得分:6)

在发布问题时,我注意到我在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;
        });

以防有人犯这样的愚蠢错误。这是我的解决方案。

当您多次订阅请求时会出现问题,因此会多次执行。解决方案是共享请求或订阅一次。我不确定在没有重新加载的情况下共享请求多个订阅的确切方法希望有人会确认这一点。我试过了.share().subscribe(),但似乎并不适合我。