是否可以使用nswag(TypeScript)自动生成自定义HTTP标头

问题描述 投票:1回答:1

我使用nswag npm package生成http服务,接口等。

典型服务代理的typescript代码如下所示:

@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) => {
        ...

关于HTTP Headers详细说明的位:

我想知道是否有办法告诉nswag工具自动添加额外的标题(在我的情况下为JWT Bearer添加Authorization)?

当然,使用文本编辑器使用以下代码替换头部位有一种hacky解决方法:

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

但我怀疑可能有一种方法可以包含额外的标题。

也许有人已经解决了这个问题?

angular typescript http-headers swagger-codegen nswag
1个回答
2
投票

启用UseTransformOptionsMethod,设置ClientBaseClass并使用扩展代码在基类中定义方法...

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

© www.soinside.com 2019 - 2024. All rights reserved.