angular - Angular - 没有重载匹配此调用。最后一个重载给出了以下错误
问题描述
以下是token.get()
我的 Angular-12 应用程序中的代码:
get(){
return localStorage.getItem('token');
}
然后我的服务中有以下提到的代码:
//GET Method
public getAllTerms(): Observable<any> {
const headers = { //Token for API Authorization
'Authorization' : this.token.get(),
'X-Requested-With' : 'XMLHttpRequest'
}
return this.http.get(`${this.api.baseURL}core/students`, headers);
}
我的 POST 给了我一个没有任何回应。但是在 Angular 中,我得到了这个错误:
No overload matches this call.
The last overload gave the following error.
Type '{ Authorization: string | null; '
X - Requested - With ': string; }'
has no properties in common with type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; context?: HttpContext | undefined; observe?: "body" | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.ts(2769)
http.d.ts(1149, 5): The last overload is declared here.
const headers: {
Authorization: string | null;
'X-Requested-With': string;
标头突出显示
如果我将其更改为:
public getAllTerms(): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.http.get(`${this.api.baseURL}core/students`, { headers, responseType: 'json' });
}
错误更改为:
401(未经授权)
我该如何解决这个问题?
解决方案
get(){
return localStorage.getItem('token');
}
null
如果令牌不存在,则
可以返回,因此其定义隐含如下: get(): string | null
。
由于 Angular 使用打字稿,所以它是严格类型的,所以string | null
!= string
。
我想这会解决你的问题:
get(): string {
return localStorage.getItem('token') ?? 'unauthenticated';
// ?? operator is explained here https://indepth.dev/posts/1300/double-question-marks-typescript-3-7-nullish-coalescing
}
推荐阅读
- yql - 是否有替代刚刚关闭的 query.yahooapis.com YQL 服务?
- jquery - 复选框在带有 jQuery 检查取消选中功能的表行中不起作用
- javascript - 保存的示例中的局部变量在哪里?
- c++ - 使用 MinGW gcc/g++ (nuwen distro) 编译的程序中的运行时错误
- python - Pyspark - 与 SparkContext 相关的错误 - 没有属性 _jsc
- postgresql - 使用 Postgres LTREE 时如何将参数传递给 JPA?
- amazon-web-services - AWS EC2 t2.small 实例 CPU 利用率每天都会定期达到 100%
- powershell - 删除集群资源依赖:SQL Server 故障转移集群
- spring-boot - SpringBoot:杰克逊 2.9.7 -> 杰克逊 2.9.8+
- ruby-on-rails - 发布请求后访问 URL 中的旧获取参数