简体   繁体   English

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

[英]Why isn't my function returning the proper JSON data and how can I access it?

I'm running services to retrieve data from an API. 我正在运行服务以从API检索数据。 Here is one of the services: 这是其中一项服务:

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

The data shows up properly on the console, but I still can't access the individual keys: 数据正确显示在控制台上,但是我仍然无法访问各个键: 安慰

Here is how I call it: 这是我的称呼:

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

When I call this function and assign it to a variable, it shows up on console as [object Object]. 当我调用此函数并将其分配给变量时,它在控制台上显示为[object Object]。 When I tried to use JSON.parse, it throws the error: type subscription is not assignable to parameter string. 当我尝试使用JSON.parse时,它引发错误:类型订阅无法分配给参数字符串。 How can I access the data? 如何访问数据? I want to take the JSON object and save it as an Object with appropriate attributes. 我想获取JSON对象并将其另存为具有适当属性的对象。 Thanks! 谢谢!

Do not subscribe inside your service, do subscribe in your component, change your service as follows, 不要在您的服务内订阅,请在您的组件中订阅,如下更改服务,

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

and then in your component, 然后在您的组件中,

ngOnInit(){
        this.api..getRobotSummary.robotSummary(this.core_id, this.channel_name).subscribe((data) => {
        this.data = data;
        console.log(this.data); 
});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM