从json加载远程数据

时间:2019-07-10 10:23:46

标签: angular cors ionic4

我正在用ionic4开发混合实时流媒体应用程序。我必须从json加载远程数据才能获取我的频道的网址以进行实时流式传输。我正在使用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)
    }
  });
}

homepage.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'.

Error image

1 个答案:

答案 0 :(得分:1)

requestOptions对象初始化中存在错误。您可以提供类型为{ [param: string]: string | string[]; }的对象。

const requestOptions = {
    headers: headerDict
};

或使用HttpHeaders类而不是Headers