首页 > 解决方案 > 为什么我的函数没有返回正确的 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 对象并将其保存为具有适当属性的对象。谢谢!

标签: jsonangularhttpclient

解决方案


不要在您的服务中订阅,请在您的组件中订阅,如下更改您的服务,

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); 
});
}

推荐阅读