拦截http响应时发送请求两次

时间:2017-10-17 10:00:32

标签: angular typescript rxjs

当我们拦截HTTP响应并使用subscribe获取Observable响应中的值时,它注意到请求被触发了2次。以下是代码

通过扩展(http.service.ts)来截取Http请求和响应

import { Injectable } from '@angular/core';
import { Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers, ConnectionBackend } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { LoggedInUserApi } from './loggedInUser.service';

@Injectable()
export class HttpService extends Http {

    constructor(private loggedInUserApi: LoggedInUserApi, backend: XHRBackend, options: RequestOptions) {
        super(backend, options);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options));
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.get(url, options));
    }

    post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.post(url, body, options));
    }

    put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.put(url, body, options));
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.delete(url, options));
    }
    handleResponseHeader(header) {
        console.log(header);
    }
    intercept(observableResponse: Observable<Response>): Observable<Response> {
        observableResponse.subscribe(response => this.handleResponseHeader(response.headers));
        return observableResponse;
    }
}

我相信订阅可观察的回复导致了这个问题。如果我们使用.subscribe的.map instad,那么问题是可重现的,但是没有得到所需的结果,例如标题值不会从响应中返回

在app.module.ts中我们指定使用HttpService而不是Http (app.module.ts)

.....
 providers: [
  ......
    {
      provide: Http,
      useFactory: (loggedInUserApi: service.LoggedInUserApi, xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
        new service.HttpService(loggedInUserApi, xhrBackend, requestOptions),
      deps: [service.LoggedInUserApi, XHRBackend, RequestOptions]
    }
  ],

...

在服务中,我们使用post方法调用服务器API来添加用户。此API调用已进行2次,这就是问题所在。它应该只触发一次。的(用户operation.service.ts)

  public addUser(body: models.User, extraHttpRequestParams?: any): Observable<models.User> {
        // verify required parameter 'body' is not null or undefined
        if (body === null || body === undefined) {
            throw new Error('Required parameter body was null or undefined when calling addUser.');
        }

        const path = this.basePath + '/user';

        let queryParameters = new URLSearchParams();
        let headerParams = new Headers({ 'Content-Type': 'application/json' });

        let requestOptions: RequestOptionsArgs = {
            method: 'POST',
            headers: headerParams,
            search: queryParameters
        };
        requestOptions.body = JSON.stringify(body);

        return this.http.request(path, requestOptions)
            .map((response: Response) => {
                if (response.status === 204) {
                    return undefined;
                } else {
                    return response.json();
                }
            }).share();
    }

在用户组件中,我们使用按钮单击事件调用服务并传递用户模型。的(User.component.ts)

addUser(event) {
    // To add user using api
    this.busy = this.api.addUser(this.user)
      .subscribe(
      () => {
        DialogService.displayStatusMessage({ message: 'User configurations saved successfully.', type: 'success' });
        this.router.navigate(['users']);
      },
      (error: any) => {
        throw ({ message: error.json().message });
      }
      );
  }

我已经阅读了类似的问题,它解释了冷和热的可观察量,我们应该使用.share来使可观察的热点和避免问题。我试过了,没有运气。

1 个答案:

答案 0 :(得分:3)

您的intercept方法订阅了一个observable,并将其返回。消费代码订阅了同样精确的可观察性。

对于与Http相关的observable,两个订阅意味着两个API调用。

intercept(observableResponse: Observable<Response>): Observable<Response> {
    observableResponse
      .subscribe(response =>                           // <-- pretty bad!
        this.handleResponseHeader(response.headers)
      );
    return observableResponse;
}

您要做的是使用用于副作用的.do()运算符。此运算符不会修改Observable类型也不会修改事件值,只需“解包”它,对值执行一些操作,然后将事件传递给流。

intercept(observableResponse: Observable<Response>): Observable<Response> {
    return observableResponse
      .do(response => this.handleResponseHeader(response.headers));
}