json - 为什么我的函数没有返回正确的 JSON 数据,我该如何访问它?
问题描述
我正在运行服务以从 API 检索数据。这是其中一项服务:
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token;
const myObject: any = {core_id : core_id, channel_name: channel_name};
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/',options)
.subscribe(
res => console.log(res),
)
}
}
我是这样称呼它的:
ngOnInit(): void{
this.login.getData(this.username, this.password).subscribe((data) => {
this.robotSummaryData = this.getRobotSummary.robotSummary(this.core_id, this.channel_name);
console.log("robosummary"+ this.robotSummaryData)
});
}
当我调用此函数并将其分配给变量时,它在控制台上显示为 [object Object]。当我尝试使用 JSON.parse 时,它会抛出错误:类型订阅不可分配给参数字符串。如何访问数据?我想获取 JSON 对象并将其保存为具有适当属性的对象。谢谢!
解决方案
不要在您的服务中订阅,请在您的组件中订阅,如下更改您的服务,
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token; const myObject: any = { core_id: core_id, channel_name: channel_name };
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/', options)
.map((response: Response) => response);
}
然后在你的组件中,
ngOnInit(){
this.api..getRobotSummary.robotSummary(this.core_id, this.channel_name).subscribe((data) => {
this.data = data;
console.log(this.data);
});
}
推荐阅读
- oracle - 过时的最后更改日期
- database - 带有 ORDER BY 的文档 DB SDK 导致 ServiceUnvailableException
- android - FragmentStateAdapter 抛出 java.lang.IllegalStateException:配置更改后违反设计假设
- excel - 执行脚本时隐藏powershell窗口
- asp.net-core - 参数类型不能为空
- javascript - 获取 eslint 快速修复以在 VSCode 中为 HTML 中的 JavaScript 工作
- google-awareness - Awareness API 失败,状态码为 12
- python-3.x - 带有for循环的函数中的嵌套函数
- nextcloud - 我想要NextCloud的所有API
- gridview - 从kartik gridview导出到excel时出现403错误