Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  5] [ 2]  / answers: 1 / hits: 15531  / 5 Years ago, wed, june 26, 2019, 12:00:00

I am trying make an http get() request by passing some values in headers, Now i am replacing the headers like this:



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();<=====
}

}


When i replace the headers like this:



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



The default headers values(i,e Content-Type : application/json) will be replaced by the above headers.



enter
Instead of replacing the headers how can i add custom headers, I tried like this:



  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();
}


What's wrong with my approach, I am new to angular, Any help?


More From » node.js

 Answers
18

You should add header to your get request like this. Also since HttpHeaders is immutable object you have to reassign header object


  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();
}

[#51959] Tuesday, June 18, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
louiseb

Total Points: 368
Total Questions: 107
Total Answers: 107

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
;