没有重载匹配这个调用。最后一次重载给出了以下错误。类型 '"text"' 不能分配给类型 '"json"'

Mun*_*kin 2 javascript xmlhttprequest jwt angular angular-httpclient

我正在尝试使用 Angular 从我的 API 获取 HTML 页面,并在标头中使用 JWT 令牌。但是,如果我不指定文本类型,编译器会发出无法解析的错误(然后它会尝试将 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));
}
}
Run Code Online (Sandbox Code Playgroud)

我尝试将内容类型删除或更改为 text/html ,但没有任何效果。


我的 API 响应:

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

San*_*tos 9

我是这样做的:

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


Mik*_*123 6

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

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

this.http.get<string>('https://cors-anywhere.herokuapp.com//sf/ask/tagged/angular/', 
    requestOptions)
        .subscribe(response => {
               console.log(response);
        }
);
Run Code Online (Sandbox Code Playgroud)