2017-08-06 440 views
2

我已经在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; 
     }); 

回答

1

虽然张贴我注意到,我订阅我的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(),但似乎没有为我工作。

+0

除了现在我没有订阅时,“401未经授权”发生。有办法解决这个问题吗? – LogicDev

+1

如果你添加了res = res.map',那么你将不会返回带有catch的观测值,这里你将res分配给结果 - 这是否有意义,还是应该单独回答? – 0mpurdy

+0

@ 0mpurdy我也这么认为。我更新了我的代码,它工作。我也更新了我的答案。 – LogicDev