Получить Http заголовки ответа и контент Angular 6 - PullRequest
0 голосов
/ 13 ноября 2018

У меня есть следующий метод веб-сервера, который возвращает данные нашему клиентскому приложению.

[FunctionName("SearchCustomerBySearchTerm")]
public static async Task<HttpResponseMessage> SearchCustomerBySearchTerm([HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Get, Route = "Customer/SearchCustomerBySearchTerm/{searchTerm}/pageSize/{pageSize}")]HttpRequestMessage req, TraceWriter log, string searchTerm, int pageSize)
{
    try
    {
        var continuationToken = req.Headers.TryGetValues("continuationToken", out IEnumerable<string> values) ? values.FirstOrDefault() : null;
        PagedResponse<CustomerSearchResult> pagedResponse = await _customerComponent.FindCustomerBy(searchTerm, continuationToken, pageSize);

        if (pagedResponse == null) return req.CreateResponse(HttpStatusCode.NoContent, $"Could not find any data related to {searchTerm}");

        HttpResponseMessage responseMessage = req.CreateResponse(HttpStatusCode.OK, pagedResponse.Results);
        responseMessage.Content.Headers.Add("continuationToken", pagedResponse.Continuation);
        responseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "*");

        return responseMessage;
    }
    catch (Exception ex)
    {
        log.Error(ex.Message);
        return req.CreateResponse(HttpStatusCode.InternalServerError, "Something went wrong. Could not search for customers");
    }
}

Я разрешаю открывать все заголовки, добавив Access-Control-Expose-Headers.

Из моего приложения Angular я делаю запрос следующим образом:

searchCustomersPaged(searchTerm: string, continuationToken: string): Observable<HttpResponse<CustomerSearchResult>> {
    let customHeaders = new HttpHeaders().set("continuationToken", this.currentContinuationToken);
    const url = "http://localhost:7071/api/Customer/SearchCustomerBySearchTerm/andrew/pageSize/10";
    const parsedUrl = encodeURI(url);
    return this.http.get<HttpResponse<CustomerSearchResult>>(parsedUrl, { headers: customHeaders });
  }

Как вы можете видеть выше, я ожидаю HttpResponse<CustomerSearch> назад.

Вот как я пытаюсь прочитать мои заголовки:

nextClikcedHandle(continuationToken: string): void {
this.customerService.searchCustomersPaged(this.customerService.searchTerm, this.currentContinuationToken)
.subscribe(resp => {
  //add current continuation token, to previous now, as this will be used for 'previous' searching
  this.previousContinuationTokens.push(this.currentContinuationToken);

  //set next continuation token received by server
  this.currentContinuationToken = resp.headers.get('continuationToken');

  //return search results
  this.customerService.searchResults.next(resp.body);
});

}

С приведенным выше кодом resp.headers и resp.body всегда равны undefined. Почему это происходит?

Если я посмотрю на вкладку Network в Chrome, я увижу, что мои данные возвращаются, а также мой заголовок.

enter image description here

Что я делаю не так?

1 Ответ

0 голосов
/ 13 ноября 2018

Я нашел полезную статью здесь :

По умолчанию HttpClient возвращает тело ответа. Вы можете передать объект с ключом наблюдения, установленным в значение «response» для получить полный ответ. Это может быть полезно для проверки наверняка заголовки:

Поэтому я изменил свой код следующим образом, добавив ключ observe.

searchCustomersPaged(searchTerm: string, continuationToken: string): Observable<HttpResponse<CustomerSearchResult>> {
    let customHeaders = new HttpHeaders().set("continuationToken", this.currentContinuationToken);
    const url = "http://localhost:7071/api/Customer/SearchCustomerBySearchTerm/andrew/pageSize/10";
    const parsedUrl = encodeURI(url);
    return this.http.get<CustomerSearchResult>(parsedUrl, { headers: customHeaders, observe: 'response' });
  }

После изменения описанного выше метода я мог запросить тело и заголовки в соответствии с нормой:

nextClikcedHandle(continuationToken: string): void {
this.customerService.searchCustomersPaged(this.customerService.searchTerm, this.currentContinuationToken)
.subscribe(resp => {
  //add current continuation token, to previous now, as this will be used for 'previous' searching
  this.previousContinuationTokens.push(this.currentContinuationToken);

  //set next continuation token received by server
  this.currentContinuationToken = resp.headers.get('continuationToken');

  //return search results
  this.customerService.searchResults.next(resp.body);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...