javascript - Angular 两次发送 http 请求

标签 javascript angular typescript

我用 Angular 4 编写了一个应用程序。看起来每次我尝试访问 API 时,angular 都会发出 2 个请求。我的应用程序中的所有方法都会发生这种情况,包括;获取、删除、放置、发布

我将在下面添加一些代码示例。例如,我有一个 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;
        });

最佳答案

在发布问题时,我注意到我订阅了我的 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() 但似乎对我不起作用。

关于javascript - Angular 两次发送 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45534491/

相关文章:

typescript - 强制对象包含枚举的所有键,并且仍然对其值进行类型推断

javascript - 获取多个 touchend 事件 javascript

javascript - 第 6 行中未关闭的 INDENT (CoffeeScript) 编译器错误

javascript - 如何延迟 Tween.js 动画直到单击按钮? (三.js)

html - 为特定组件启用滚动

angular - 无法在 Angular 项目上安装 typescript@4.9

javascript - datejs TimeSpan 和 TimePeriod 问题

inheritance - 以编程方式插入不同的 Angular2 组件

angular - 提供了重复的列名 : Angular Material Data Table

reactjs - 将 Redux-Form 与 React-Redux connect 结合使用时出现 TypeScript 错误