为什么我的函数没有返回正确的JSON数据,我该如何访问它?

时间:2018-06-18 02:24:07

标签: json angular httpclient

我正在运行服务以从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),
        )
   }
}

数据在控制台上正确显示,但我仍然无法访问各个键: console

以下是我的称呼方式:

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时,它会抛出错误:type subscription不能赋值给参数字符串。我如何访问数据?我想获取JSON对象并将其保存为具有适当属性的Object。谢谢!

1 个答案:

答案 0 :(得分:2)

请勿在您的服务中订阅,订阅您的组件,更改您的服务,如下所示,

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