0

I'm running services to retrieve data from an 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: console

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]. When I tried to use JSON.parse, it throws the error: type subscription is not assignable to parameter string. How can I access the data? I want to take the JSON object and save it as an Object with appropriate attributes. Thanks!

may
  • 79
  • 1
  • 7
  • Assign what specifically to a variable? Is this just the normal async issue? – Dave Newton Jun 18 '18 at 02:28
  • I want to assign for example the "state" key as an attribute to an object. I don't understand what you mean by normal async issue? – may Jun 18 '18 at 02:30

1 Answers1

2

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); 
});
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396