Angular: HttpRequest.clone () - В чем разница между params и setParams? - PullRequest
1 голос
/ 27 сентября 2019

У меня есть перехватчик:

intercept(request, next) {
  const _id = 1
  const _token = "foo"
  return next.handle(request.clone({ 
    setParams: {
     user_id: _id,
     user_token: _token
    }
  });
}

Я заметил, что вместо setParams есть поле params?

В документах на веб-сайте Angular отсутствует информация для класса HttpRequest.Он показал, что они были там, но не было никакой информации.

Является ли params жестким переопределением, и setParams способ добавления дополнительных пар Key->Value к запросу?

1 Ответ

1 голос
/ 27 сентября 2019

Метод HttpRequest.clone() обеспечивает перегрузку, которая поддерживает передачу объекта update:

clone(update: { headers?: HttpHeaders; reportProgress?: boolean; 
  params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; 
  withCredentials?: boolean; body?: T; method?: string; url?: string; 
  setHeaders?: { ...; }; setParams?: { ...; }; }): HttpRequest<T>
  • params - Предоставляетопция назначить параметры HTTP с экземпляром HttpParams, перезаписывая существующие параметры в процессе.
  • setParams - Предоставляет возможность добавлять HTTP-параметры с использованием литерала объекта, где ключами являются имена параметров, которые должны быть установлены.

Исходный код для clone() метода

clone(update: {
  headers?: HttpHeaders,
  reportProgress?: boolean,
  params?: HttpParams,
  responseType?: 'arraybuffer'|'blob'|'json'|'text',
  withCredentials?: boolean,
  body?: any|null,
  method?: string,
  url?: string,
  setHeaders?: {[name: string]: string | string[]},
  setParams?: {[param: string]: string};
} = {}): HttpRequest<any> {
  // For method, url, and responseType, take the current value unless
  // it is overridden in the update hash.
  const method = update.method || this.method;
  const url = update.url || this.url;
  const responseType = update.responseType || this.responseType;

  // The body is somewhat special - a `null` value in update.body means
  // whatever current body is present is being overridden with an empty
  // body, whereas an `undefined` value in update.body implies no
  // override.
  const body = (update.body !== undefined) ? update.body : this.body;

  // Carefully handle the boolean options to differentiate between
  // `false` and `undefined` in the update args.
  const withCredentials =
      (update.withCredentials !== undefined) ? update.withCredentials : this.withCredentials;
  const reportProgress =
      (update.reportProgress !== undefined) ? update.reportProgress : this.reportProgress;

  // Headers and params may be appended to if `setHeaders` or
  // `setParams` are used.
  let headers = update.headers || this.headers;
  let params = update.params || this.params;

  // Check whether the caller has asked to add headers.
  if (update.setHeaders !== undefined) {
    // Set every requested header.
    headers = Object.keys(update.setHeaders)
        .reduce((headers, name) => headers.set(name, update.setHeaders ![name]), headers);
  }

  // Check whether the caller has asked to set params.
  if (update.setParams) {
    // Set every requested param.
    params = Object.keys(update.setParams)
        .reduce((params, param) => params.set(param, update.setParams ![param]), params);
  }

  // Finally, construct the new HttpRequest using the pieces from above.
  return new HttpRequest(
      method, url, body, { params, headers, reportProgress, responseType, withCredentials, });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...