首页 > 解决方案 > 从 json 加载远程数据

问题描述

我正在 ionic4 中开发一个混合直播应用程序。我必须从 json 加载远程数据以获取我的直播频道的 url。我正在使用 http 方法从 json 获取数据,但出现错误:

请求的资源上不存在“Access-Control-Allow-Origin”标头。

所以这就是为什么我使用 IONIC 的 CORS 策略来避免这个错误。但现在我面临的错误

Types of property 'headers' are incompatible.
[ng]  Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
[ng]    Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.
[ng]    Index signature is missing in type 'Headers'.

我正在使用 http 方法从 json 获取数据,但我收到“请求的资源上不存在‘Access-Control-Allow-Origin’标头”的错误。所以这就是为什么我使用 IONIC 的 CORS 策略来避免这个错误。

加载数据的功能:

reddit-data.Service.ts

getRemoteData() {
  const headerDict = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Access-Control-Allow-Headers': 'Content-Type',
  }
  const requestOptions = {
    headers: new Headers(headerDict),
  };
  this.http.get("url", requestOptions).subscribe((res) => {
    //console.log(data);
    err => {
      console.log(err)
    }
  });
}

主页.ts

ngOnInit() {
  this.redditService.getRemoteData();
}

我收到标题错误:

[ng] ERROR in src/app/services/reddit-data.service.ts(56,75): error TS2345: Argument of type '{ headers: Headers; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'.
[ng]  Types of property 'headers' are incompatible.
[ng]    Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
[ng]    Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.
[ng]    Index signature is missing in type 'Headers'.

错误图片

标签: angularionic4

解决方案


您的requestOptions对象初始化有错误。您可以提供一个 Object 类型{ [param: string]: string | string[]; }

const requestOptions = {
    headers: headerDict
};

或使用HttpHeaders类而不是Headers.


推荐阅读