1

I use nswag npm package to generate http services, interfaces, etc.

The typescript code for a typical service proxy looks as follows:

@Injectable()
export class TenantsServiceProxy {
...
    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
    ...

    getTenantId(subdomain: string | null): Observable<number | null> {
    ...
        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Content-Type": "application/json", 
                "Accept": "application/json"
                })
            };

        return this.http.request("get", url_, options_).flatMap((response_ : any) => {
            return this.processGetTenantId(response_);
        }).catch((response_: any) => {
        ...

Regarding the bit where HTTP Headers are detailed:

I wonder if there's a way to tell the nswag tool to add an extra header (Authorization for JWT Bearer in my case) automatically?

Of course there's sort of a hacky workaround to replace the headers bit using text editor with the following code:

headers: new HttpHeaders({
            "Content-Type": "application/json", 
            "Accept": "application/json",
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        })

But I suspect there might be a way to include additional headers.

Maybe someone has already solved this issue?

Alex Herman
  • 2,708
  • 4
  • 32
  • 53

1 Answers1

2

Enable UseTransformOptionsMethod, set a ClientBaseClass and define the method in the base class with extension code...

See https://github.com/RSuter/NSwag/wiki/SwaggerToTypeScriptClientGenerator#transform-the-options-or-the-result

Rico Suter
  • 11,548
  • 6
  • 67
  • 93
  • 1
    The link above doesn’t work anymore. New link: https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator#transform-the-options-or-the-result – Albert Hoekstra Apr 04 '20 at 17:59
  • options.headers.append("myheader", "myvalue"); did not work for me in Angular. I had to change it to options.headers = options.headers.append("myheader", "myvalue"); because HttpHeaders is immutable, but appending and reassigning does the trick – Jiren Mar 20 '22 at 16:21