Angular - OpenApi CodeGen - 如何在 api 请求中添加标题?

问题描述

我正在使用 Angular 10。我正在使用 openapi codegen(自动生成)服务。

问题:我想在我的标头中传递 Authorization: Token 123456,但似乎无法弄清楚如何以及在何处添加拦截器。

我的组件文件是:

 constructor(        
    private meApi : MeService
    )


 meDetails;
  meCheck(){
      this.meApi.meRead().subscribe(
        (data: any) => {
          this.meDetails= data;
        },(err) => { console.error(err); },() => { }
      )
    }

在 ngOnInIt 中运行此函数时。我收到以下错误:

401 (Unauthorized)

因为很明显,授权令牌没有通过 API 传递。

自动生成的服务文件中的meRead()函数有如下相关代码:

 /**
     * @param observe set whether or not to return the data Observable as the body,response or events. defaults to returning the body.
     * @param reportProgress flag to report request and response progress.
     */
    public meRead(observe?: 'body',reportProgress?: boolean,options?: {httpHeaderAccept?: 'application/json'}): Observable<User>;
    public meRead(observe?: 'response',options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<User>>;
    public meRead(observe?: 'events',options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<User>>;
    public meRead(observe: any = 'body',reportProgress: boolean = false,options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {

        let headers = this.defaultHeaders;

        // authentication (DRF Token) required
        if (this.configuration.apiKeys) {
            const key: string | undefined = this.configuration.apiKeys["DRF Token"] || this.configuration.apiKeys["Authorization"];
            if (key) {
                headers = headers.set('Authorization',key);
            }
        }

        let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
        if (httpHeaderAcceptSelected === undefined) {
            // to determine the Accept header
            const httpHeaderAccepts: string[] = [
                'application/json'
            ];
            httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
        }
        if (httpHeaderAcceptSelected !== undefined) {
            headers = headers.set('Accept',httpHeaderAcceptSelected);
        }

如何在此请求的标头中传递 Authorization: Token 12345?

总结:如何在 openapi 代码生成服务文件中传递 Authorization 标头?

如果您能给出详细的答案,将不胜感激。谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)