没有过载匹配此调用。最后一个重载给出了以下错误。类型“"text"”不可分配给类型“"json"”

No overload matches this call. The last overload gave the following error. Type '"text"' is not assignable to type '"json"'

我正在尝试使用 Angular 和 header 中的 JWT 令牌从我的 API 获取 HTML 页面。但是,如果我没有指定文本类型,编译器会吐出一个无法解析的错误(然后它会尝试将 HTML 解析为 JSON),所以我需要指定我的响应类型。

这是我的 component.ts:

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'Bearer TOKENHERE'
    })
  };
  constructor(private http: HttpClient) { }

  ngOnInit() {


  }
  fetchDashboard() {
    this.http.get('http://localhost:3000/avior/dashboard', {responseType: 'text', this.httpOptions,}).subscribe(j => console.log(j));
}
}

我尝试删除 content-type 或将其更改为 text/html,但没有任何效果。


我的API回复:

<html><head><title>Dashboard</title></head><body><h1>Dashboard works!</h1></body></html>

您可以在您的组件中尝试以下操作,看看您的呼叫是否适用于另一个网站。下面应该return请求页面的html作为一个字符串。如果这对您的 API 不起作用,那么问题可能不是您在组件中的代码,而是您的 API 的响应是 returning

const requestOptions: Object = {
  headers: new HttpHeaders().append('Authorization', 'Bearer <yourtokenhere>'),
  responseType: 'text'
}

this.http.get<string>('https://cors-anywhere.herokuapp.com/https://whosebug.com/questions/tagged/angular', 
    requestOptions)
        .subscribe(response => {
               console.log(response);
        }
);

我是这样做的:

    getDivisionName(x: string): Promise<any> {
    return this.httpClient
      .get<any>(this.serviceUrl + `/something/${x}/`, {
        responseType: 'text' as 'json',
      })
      .toPromise();
  }