angular - 从 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'.
解决方案
您的requestOptions
对象初始化有错误。您可以提供一个 Object 类型{ [param: string]: string | string[]; }
。
const requestOptions = {
headers: headerDict
};
或使用HttpHeaders类而不是Headers
.
推荐阅读
- flutter - 如何在一个 ListView 中使用多个 StreamBuilder
- c++ - 结转数据而不使用 for 循环
- python - 使用 plt.plot 绘制图表时遇到问题
- laravel - Laravel 日志文件权限问题
- wordpress - 如何仅重写 Wordpress 主页 url?
- python - 模板文件中的静态块标签无效
- jquery - 根据下拉选择值显示/隐藏元素
- java - 我们应该在 java 测试文件夹还是主文件夹中编写 testng selenium 代码?
- spring-boot - 使用 Facebook 登录:错误请求。主机和端口的这种组合需要 TLS
- django - 如何使用 kwargs 正确初始化类实例