如何解决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 标头?
如果您能给出详细的答案,将不胜感激。谢谢。
解决方法
您可以通过更改生成的客户端的 defaultHeaders 属性或通过在 ad-hoc 属性中提供一些配置来传递标头。 请参阅此 blog post 以了解其他一些选项。
/**
* OpenAPI definition [...]
*/
import { ...}
@Injectable({
providedIn: 'root'
})
export class UserControllerService {
protected basePath = 'http://localhost:8081';
public defaultHeaders = new HttpHeaders(); // <- here
public configuration = new Configuration(); // <- or there
public encoder: HttpParameterCodec;
{...}
}
至于通过方法调用的 {httpHeaders: '/'} 传递一些有用的东西,不知道该怎么做。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。