What is the standard practice to set custom headers in Angular?

To have a global setHeader function in a service file, where every get request calls this function

app.component.ts

 getData() {
        const url = `myurl`;
        var param = {"data1": this.data1,"data2": this.data2}
        var headerObj = {"header1": this.header1,"header2": this.header2,}
        this.dataService.getRequest(url, param, headerObj)
            .subscribe((data) => {});
    }

dataService.ts

setHeaders(header) {
    var httpHeaders = new HttpHeaders();
    header.forEach((key, value) => {
        httpHeaders = httpHeaders.append(key, value);
    });
    return httpHeaders
}
getRequest(endPoint: String, param: any, header: any) {
    const httpHeaders = this.setHeaders(header);
    return this.http.get<any>(url, {
        headers: httpHeaders,
        params: param
    })
}

OR Passing header from app.component function into dataService.ts get request function

app.component.ts

getData() {
    const url = `myurl`;
    var param = {"data1": this.data1,"data2": this.data2,}
    let headers = new HttpHeaders()
    .set('header1', this.header1)
    .set('header2', this.header2);
    this.dataService.getRequest(url, param, headers)
    .subscribe((data) => {});
}

dataService.ts

getRequest(endPoint: string, params: any, headers: HttpHeaders) {
    return this.http.get<any>(endPoint, {
        headers: headers,
        params: param
    })
}
0

There are 0 best solutions below