在订阅中被访问时请求的响应不相同

时间:2018-12-28 11:58:45

标签: angular httprequest angular-http angular-http-interceptors angular4-httpclient

我有一个角度函数,它可以对某个端点进行HTTP调用,并且正在订阅响应。但是有一种非常奇怪的行为,我注意到,当我在“网络”选项卡中检查请求的响应时,它是正确的,但是当我在console.log中的console中看到非常相同的请求的相同响应时,情况就不同了。 这是我的角度函数,它正在发出请求并订阅响应。

getTemplate(){
    this.documentService.getDocumentTemplates({}, this.template_uuid)
      .subscribe((response) => {
        console.log('response');
        console.log(response);
        this.questionsarray = response['questions'];
        let i = 0;
        for (const section  of this.questionsarray) {
          for (const question of section.questions) {
            this.questionsarray[i] = question;
            i++;
          }
        }
        if(this.action === 'edit'){
          this.getContract(this.contractUUID);
        }
    });
  }

,以下是“网络”标签的屏幕截图 enter image description here

,以下是console.log的屏幕截图 enter image description here

我无法找出我的错误,感谢您的帮助。谢谢。

编辑: 这是我的服务功能。

getDocumentTemplates(data: Object = null, uuid) {
    return this.httpService.httpRequestConsumerWithUUID({
        method: 'GET',
        url: '/agbuilder/template/' + uuid + '/',
        data: data
    });
  }

这是我的http warperer服务,该服务最终会发出请求并返回响应。

@Injectable()
export class HttpService {

  baseUrl: string = environment.serverUri;
  onError: EventEmitter<string> = new EventEmitter<string>();

  constructor(
    private http: Http,
    public router: Router,
    private cookieService: CookieService
    ) {
  }

  // for auth(login, signup and profile) where it will use accounts api+server token
  httpRequest(requestObject: any) {
    const request = this.requestBuilder(requestObject, 'server');
    return this.MakeRequest(request);
  }

  // this will use consumer token with uuid in url
  httpRequestConsumerWithUUID(requestObject: any) {
    const request = this.requestBuilder(requestObject, 'consumer-uuid');
    return this.MakeRequest(request);
  }

  // this will use consumer token WITHOUT uuid in url
  httpRequestConsumer(requestObject: any) {
    const request = this.requestBuilder(requestObject, 'consumer');
    return this.MakeRequest(request);
  }

  MakeRequest(request: any) {
    return this.http.request(request)
      .map(response => {

        if (response.status === 204) {

          return Object.assign({'status': 'success'}, {
            serverUri: environment.serverUri
          });
        }

        return Object.assign(response.json(), {
          serverUri: environment.serverUri
        });
      })
      .catch((err) => this.handleError(err));
  }


  // httpRequest(requestObject: any) {

  //   const request = this.requestBuilder(requestObject);
  //   return this.http.request(request)
  //     .map(response => {

  //       if(response.status==204)//when server will perform DELETE operation i.e logout
  //       {
  //         return Object.assign({name: 'server did not send anything'},{serverUri: environment.serverUri});//sending dummy data
  //       }
  //       return Object.assign(response.json(), {
  //         serverUri: environment.serverUri
  //       });
  //     })
  //     .catch((err) => this.handleError(err));
  // }

  handleError(error: Response) {
    if (error.status === 401) {
      window.localStorage.clear();
      window.location.href = environment.login_url;
    }
    return Observable.throw(error || { '_body': 'Server error' });
  }

  private requestBuilder(requestObject: any, reqType: string): Request {
    let method: RequestMethod;
    switch (requestObject.method) {
      case 'GET':
        method = RequestMethod.Get;
        break;
      case 'POST':
        method = RequestMethod.Post;
        break;
      case 'PUT':
        method = RequestMethod.Put;
        break;
      case 'PATCH':
        method = RequestMethod.Patch;
        break;
      case 'DELETE':
        method = RequestMethod.Delete;
        break;
      default:
        throw new Error('Property `method` is required for `http request`');
    }
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');

    const access_token = window.localStorage.getItem('token') || null;

    switch (requestObject.wukla) {
      case 'false': // if using wukla APIs
        this.baseUrl = environment.serverUri;
        break;
      default: // for calls with server token
        this.baseUrl = environment.wuklaServerUri;
        // const access_token = window.localStorage.getItem('consumer_token') || null;

    }

    const data = Object.assign({}, requestObject.data);
    if (reqType === 'server') {

      // const access_token = window.localStorage.getItem('token') || null;
      // if (access_token) {
        // headers.append('Authorization', 'JWT ' + access_token);
      // }

      headers.append('X-CSRFToken', this.cookieService.get('csrftoken'));

        const request: Object = {
          method: method,
          url: (this.baseUrl + requestObject.url),
          headers: headers,
          body: JSON.stringify(data),
          withCredentials: true,
        };
        return new Request(new RequestOptions(request));
    } else if (reqType === 'consumer-uuid') {

    // const access_token = window.localStorage.getItem('consumer_token') || null;
    // if (access_token) {
      // headers.append('Authorization', 'JWT ' + access_token);
    // }

      headers.append('X-CSRFToken', this.cookieService.get('csrftoken'));

      const request: Object = {
        method: method,
        url: (this.baseUrl + '/profile/' + this.getUUID() + requestObject.url),
        headers: headers,
        body: JSON.stringify(data),
        withCredentials: true,
      };
      return new Request(new RequestOptions(request));
    } else if (reqType === 'consumer') {

      // const access_token = window.localStorage.getItem('consumer_token') || null;
      // if (access_token) {
      //   headers.append('Authorization', 'JWT ' + access_token);
      // }

      headers.append('X-CSRFToken', this.cookieService.get('csrftoken'));

        const request: Object = {
          method: method,
          url: (this.baseUrl + requestObject.url),
          headers: headers,
          body: JSON.stringify(data),
          withCredentials: true,
        };
        return new Request(new RequestOptions(request));
    }

  }

  // upload on connect
  uploadFile(url, data) {

    const headers = new Headers();
    headers.append('X-CSRFToken', this.cookieService.get('csrftoken'));

    const request: Object = {
      method: 'POST',
      url: (environment.serverUri + url),
      headers: headers,
      body: data,
      withCredentials: true,
    };
    return this.http.request(new Request(new RequestOptions(request)))
      .map(response => {
        return Object.assign(response.json(), {
          serverUri: environment.serverUri
        });
      })
      .catch((err) => this.handleError(err));
  }

  uploadFileToWukla(url, data) {

    const headers = new Headers();
    headers.append('X-CSRFToken', this.cookieService.get('csrftoken'));

    const request: Object = {
      method: 'POST',
      url: (environment.wuklaServerUri + '/profile/' + this.getUUID() + url),
      headers: headers,
      body: data,
      withCredentials: true,
    };
    return this.http.request(new Request(new RequestOptions(request)))
      .map(response => {
        return Object.assign(response.json(), {
          serverUri: environment.serverUri
        });
      })
      .catch((err) => this.handleError(err));
  }

  downloadFile(url): Observable<Blob> {

    const headers = new Headers();
    headers.append('Content-Type', 'application/pdf');
    headers.append('X-CSRFToken', this.cookieService.get('csrftoken'));

    const request: Object = {
      method: 'GET',
      url: (environment.wuklaServerUri + '/profile/' + this.getUUID() + url),
      headers: headers,
      body: JSON.stringify({}),
      responseType: ResponseContentType.Blob,
      withCredentials: true,
    };

    return this.http.request(new Request(new RequestOptions(request)))
      .map(res => res.blob())
      .catch((err) => this.handleError(err));

  }

  getUUID() {
    return window.localStorage.getItem('uuid') || null;
  }

}

编辑 这是console.log选项卡中响应对象中的问题数组。

questions: Array(4)
0:
help_text: "From which date do you want to start the Non Disclosure Agreement?"
required: true
slug: "agreement_date"
type: "DatePicker"
__proto__: Object
1:
help_text: "For how long should this NDA be for?"
required: true
slug: "agreement_validity"
type: "NumberYears"
__proto__: Object
2:
questions: (3) [{…}, {…}, {…}]
side_text: "Second Party Information"
__proto__: Object
3:
questions: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
side_text: "Non Disclosure Agreement details"
__proto__: Object
length: 4
__proto__: Array(0)

这是来自“网络”标签中响应的问题数组。

questions: [{questions: [{slug: "agreement_date", type: "DatePicker", required: true,…},…],…},…]
0: {questions: [{slug: "agreement_date", type: "DatePicker", required: true,…},…],…}
questions: [{slug: "agreement_date", type: "DatePicker", required: true,…},…]
side_text: "General Information"
1: {questions: [,…], side_text: "First Party Information"}
questions: [,…]
side_text: "First Party Information"
2: {questions: [,…], side_text: "Second Party Information"}
questions: [,…]
side_text: "Second Party Information"
3: {,…}
questions: [{slug: "nda_purpose", type: "RadioButton",…}, {slug: "nda_confidentiality", type: "CheckBoxes",…},…]
side_text: "Non Disclosure Agreement details"

1 个答案:

答案 0 :(得分:2)

当您到达questions位时,console.log(...)数组是相同的。但是,它是实时更新的(仅通过对象检查控制台上小的i信息:

Here

它将显示类似“立即评估以下值”的意思,这意味着它不是您打印时的值,而是您在控制台上打开对象时的值。

如果要在打印时使它相同,则应打印它的副本:

console.log(JSON.parse(JSON.stringify(object));

以防万一,您不知道要在哪里修改它,就在这里:

    this.questionsarray = response['questions'];
    let i = 0;
    for (const section  of this.questionsarray) {
      for (const question of section.questions) {
        this.questionsarray[i] = question;
        i++;
      }
    }

this.questionarrayresponse.questions是同一数组,因此,由于要修改一个数组,因此请同时修改两者。