как добавить пользовательские заголовки в httpRequest в угловых - PullRequest
0 голосов
/ 26 июня 2019

Я пытаюсь сделать запрос http get(), передав немного values в headers, Теперь я заменяю headers следующим образом:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {ICustomer} from 'src/app/models/app-models';

@Injectable({
  providedIn: 'root'
})
export class MyService {
private baseUrl = '....api url....';
public authKey = '....auth_key......';

  constructor(private http: HttpClient) { }

  public async AllCustomers(): Promise<ICustomer[]> {
   const apiUrl = `${this.baseUrl}/customers`;

   return this.http.get<ICustomer[]>(apiUrl ,
    {headers: new HttpHeaders({Authorization: this.authKey})}).toPromise();<=====
  }

}

Когда я заменяю заголовки, подобные этому:

headers: new HttpHeaders({Authorization: this.authKey})

Значения заголовков по умолчанию (i, e Content-Type: application / json) будут заменены вышеуказанными заголовками.

enter image description here Вместо того, чтобы заменить заголовки, как я могу добавить custom headers, я попробовал так:

  public async AllCustomers(): Promise<ICustomer[]> {
    const apiUrl = `${this.baseUrl}/courses`;
    const headers = new HttpHeaders();
    headers.append('Authorization', this.authKey);
    headers.append('x-Flatten', 'true');
    headers.append('Content-Type', 'application/json');

    return this.http.get<ICustomer[]>(apiUrl).toPromise();
  }

Что не так с моим подходом, я новичок в angular, Любая помощь?

Ответы [ 3 ]

2 голосов
/ 26 июня 2019

Вы должны добавить заголовок к вашему запросу get, как это.Кроме того, поскольку HttpHeaders является неизменным объектом, вы должны написать так:

  public async AllCustomers(): Promise<ICourses[]> {
    const apiUrl = `${this.baseUrl}/courses`;
    let headers = new HttpHeaders();
    headers = headers.append('Authorization', this.authKey);
    headers = headers.append('x-Flatten', 'true');
    headers = headers.append('Content-Type', 'application/json');

    return this.http.get<ICourses[]>(apiUrl, {headers}).toPromise();
  }
1 голос
/ 26 июня 2019

Я думаю, вы забыли добавить объект заголовка в запрос

С

return this.http.get<ICourses[]>(apiUrl).toPromise();

К

return this.http.get<ICourses[]>(apiUrl, { headers }).toPromise();
0 голосов
/ 26 июня 2019
import { HttpHeaders } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';


constructor(private _http: HttpClient) { 

}


public getHeaders(): HttpHeaders {
  const headers = new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': `Bearer ${this._auth.token}`
  });
  return headers;
}


public getData() {
  const url     = `https://stackoverflow.com/api/test`;
  const body    = { };
  const options = { headers: this.getHeaders() };
  return this._http.post<any>(url, body, options);
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...