首页 > 解决方案 > 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(未经授权)

我该如何解决这个问题?

标签: angular

解决方案


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
}

推荐阅读